java - Using Collections.sort to sort an ArrayList of a specific object -


so have seen multiple questions addressing similar problems mine, not able find 1 problem.

i have arraylist of contact objects, , want sort them using collections.sort:

public void sortcontactarraylist(){     arraylist<contact> newlist = new arraylist<contact>();     collections.sort(newlist); } 

in order this, made contactimplement comparable<contact>. and, compareto method looks this:

@override public int compareto(contact othercontact) {     return this.getname().compareto(othercontact.getname()); } 

however, receiving error when calling collections.sort(newlist);

the error is:

"bound mismatch: generic method sort(list<t>) of type collections not applicable arguments (arraylist<contact>). inferred type contact not valid substitute bounded parameter <t extends comparable<? super t>>"

does know issue is? said, have seen similar problem customized list of objects "contactdatabase<contact>" or something, have never seen problem object itself.

thank you!

it should ok if implemented comparable<contact>.

here quick test code:

contact.java:

public class contact implements comparable<contact> {      private string name;      public contact(string name) {         this.name = name;     }      public string getname() {         return name;     }      @override     public int compareto(contact othercontact) {         return this.getname().compareto(othercontact.getname());     } } 

main method:

public static void main(string[] args) {      arraylist<contact> newlist = new arraylist<contact>();     newlist.add(new contact("midgar"));     newlist.add(new contact("david"));     collections.sort(newlist);     system.out.println(newlist); } 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -