问题描述
importjava.util.*;className{privateStringfirstName;privateStringlastName;publicName(StringfirstName,StringlastName){this.firstName=firstName;this.lastName=lastName;}publicStringgetFirstName(){returnfirstName;}publicStringgetLastName(){returnlastName;}publicStringtoString(){return"firstNameis:"+firstName+"n"+"lastNameis:"+lastName;}publicbooleanequals(Objectobj){if(objinstanceofName){Namename=(Name)obj;return(firstName.equals(name.firstName))&&(lastName.equals(name.lastName));}else{returnsuper.equals(obj);}}publicinthashCode(){returnfirstName.hashCode();}publicintcompareTo(Objecto){Namen=(Name)o;intlastCmp=lastName.compareTo(n.lastName);return(lastCmp!=0?lastCmp:firstName.compareTo(n.firstName));}}publicclassTestComparable{publicstaticvoidmain(Stringargs[]){Listl1=newLinkedList();l1.add(newName("tom","a"));l1.add(newName("jame","b"));l1.add(newName("kobe","c"));System.out.println(l1);System.out.println("---------------");Collections.sort(l1);System.out.println(l1);}}运行有问题,抛异常,请大虾指点。
解决方案
解决方案二:
importjava.util.*;classNameimplementsComparable{privateStringfirstName;privateStringlastName;publicName(StringfirstName,StringlastName){this.firstName=firstName;this.lastName=lastName;}publicStringgetFirstName(){returnfirstName;}publicStringgetLastName(){returnlastName;}publicStringtoString(){return"firstNameis:"+firstName+"n"+"lastNameis:"+lastName;}publicbooleanequals(Objectobj){if(objinstanceofName){Namename=(Name)obj;return(firstName.equals(name.firstName))&&(lastName.equals(name.lastName));}else{returnsuper.equals(obj);}}publicinthashCode(){returnfirstName.hashCode();}publicintcompareTo(Objecto){Namen=(Name)o;intlastCmp=lastName.compareTo(n.lastName);return(lastCmp!=0?lastCmp:firstName.compareTo(n.firstName));}}publicclassTestComparable{publicstaticvoidmain(Stringargs[]){Listl1=newLinkedList();l1.add(newName("tom","a"));l1.add(newName("jame","b"));l1.add(newName("kobe","c"));System.out.println(l1);System.out.println("---------------");Collections.sort(l1);System.out.println(l1);}}
Name继承Comparable试试
解决方案三:
异常信息呢?
解决方案四:
static<TextendsComparable<?superT>>voidsort(List<T>list)根据元素的自然顺序对指定列表按升序进行排序。要用Collections.sort(l1);排序,这个l1对象要实现Comparable接口