generics - Java passing Comparator to constructor -


if want pass constructor comparator can compare on 2 different types, should parameter of constructor this?:

public myclass(comparator<?> comp) {   this.comp = comp; } 

then comparator class:

public namecomparator implements comparator<string> {    @override     public int compare(string s1, string s2) {         return s1.compareto(s2);     } } 

then whenever instantiate class do:

myclass myclass = new myclass(new namecomparator()); 

is correct way go doing this?

thanks

edit:

here's relevant code:

public class bst<t> {   /* binary search tree */   ...   private comparator<t> c;    /* pass in comparator constructor*/   public bst(comparator<t> c) {     this.c = c;   } 

comparator:

public class namecomparator implements comparator<string> {  @override  public int compare(string s1, string s2) {    return s2.compareto(s1);  } } 

when creating bst:

bst bst = new bst(new namecomparator()); 

your requirements seem bit special , cannot make use of generic types, because string final class, "special class" cannot extend.

you perhaps make work using marker interface, both of comparator classes need implement:

/** marker interface special comparators */ public interface specialcomparator{}  public class namecomparator implements comparator<string>, specialcomparator{     @override     public int compare(string s1, string s2) {       return s2.compareto(s1);     } }  public class bst {     /* binary search tree */     ...     private specialcomparator c;      /* pass in comparator constructor*/     public bst(specialcomparator c) {       this.c = c;     } } 

Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -