类名为StrLenComparator不会出错,类名定义为StringLengthComparator则会出现图片中的提示。
求解
- class TreeSetTest
- {
- public static void main(String[] args)
- {
- TreeSet ts=new TreeSet(new StrLenComparator());
- ts.add("abcd");
- ts.add("cc");
- ts.add("cba");
- ts.add("z");
- ts.add("hahaha");
- Iterator it=ts.iterator();
- while (it.hasNext())
- {
- sop(it.next());
- }
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
- class StrLenComparator implements Comparator
- {
- public int compare(Object o1,Object o2)
- {
- String s1=(String)o1;
- String s2=(String)o2;
- if (s1.length()>s2.length())
- {
- return 1;
- }
- if (s1.length()==s2.length())
- {
- return 0;
- }
- return -1;
- }
- }
复制代码 |