sorting - Error for Collections.sort using Comparable, Java -
first-timer here, having problem here java code: import java.util.*;
public class pootis { public static void main(string[] args) { superhero batman = new superhero("bruce", 26, "batman"); human rachel = new human("rachel", 24); superhero ironman = new superhero("tony", 35, "ironman"); human pepper = new human("pepper", 22); list<human> people = new arraylist<>(); people.add(batman); people.add(rachel); people.add(ironman); people.add(pepper); collections.sort(people);//<----- } }
the purpose of program sort people in people arraylist age. using comparable interface this. problem appears when collections.sort(people) called. did wrong?? second class:
public class human implements comparable<human> { private int age; private string name; public human(string givenname, int age) { this.name = givenname; this.age = age; } @override public int compareto(human other){ if(getage() > other.getage()){ return 1; } else if(getage() < other.getage()){ return -1; } return 0; } public string getname() { return name; } public int getage() { return age; } }
this error:
pootis.java:65: error: no suitable method found sort(list) collections.sort(people); ^ method collections.sort(list,comparator) not applicable (cannot instantiate arguments because actual , formal argument lists differ in length) method collections.sort(list) not applicable (inferred type not conform declared bound(s) inferred: object bound(s): comparable) t#1,t#2 type-variables: t#1 extends object declared in method sort(list,comparator) t#2 extends comparable declared in method sort(list) 1 error
this superhero class:
public class superhero { string alterego, name; int age; public superhero(string givenname, int age, string alterego) { super(); this.alterego = alterego; this.name = givenname; this.age = age; } public string getalterego() { return alterego; } public string introduce() { return "hey! i'm " + name + " , i'm " + age + " years old. i'm known as" + alterego + "!"; } }
the signature of collections.sort()
is:
public static <t extends comparable<? super t>> void sort(list<t> list)
this means can call sort
on list of comparable
objects. using list<object>
not valid object
not comparable
. sort()
overloaded
public static <t> void sort(list<t> list, comparator<? super t> c)
but not applicable method call you've provided 1 parameter.
bear in mind that, per javadoc, in order sort list using collections.sort()
elements must mutually comparable. in case means should have way of comparing human
superhero
. also, if superhero extends human
, list should declared list<human>
(or viceversa).
Comments
Post a Comment