今天发现,ArrayList 排序不满足期望。
起先,List是这样Before sort: [1, @I, am, Love, java, very, Much]
使用Collections.sort()方法排后是这样
After sort: [1, @I, Love, Much, am, java, very]
顺序:数字-非数字和字母字符-大写字符串(A-Z)-小写字符串(a-z)
期望的是按照字母顺序,忽略大小写
After override sort method: [1, @I, am, java, Love, Much, very]
所以只能Override sort方法
ArrayList<String> list=new ArrayList<String>(); list.add("1"); list.add("@I"); list.add("am"); list.add("Love"); list.add("java"); list.add("very"); list.add("Much"); System.out.println("Before sort: "+list); Collections.sort(list); System.out.println("After sort: "+list); Collections.sort(list,new Comparator<Object>(){ @Override public int compare(Object obj1, Object obj2) { return ((String) obj1).toUpperCase().compareTo(((String) obj2).toUpperCase()); } }); System.out.println("After override sort method: "+list); Collections.reverse(list); System.out.println("After reverse: "+list);
运行结果如下:
Before sort: [1, @I, am, Love, java, very, Much]
After sort: [1, @I, Love, Much, am, java, very]
After override sort method: [1, @I, am, java, Love, Much, very]
After reverse: [very, Much, Love, java, am, @I, 1]