- package com.itheima;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
- public class CollectionsTestDemo {
- public static void main(String args[]){
- sortDemo();
- }
- public static void sop(Object obj){
- System.out.println(obj);
- }
-
- public static void sortDemo(){
- List<String> list = new ArrayList<String>();
- list.add("zf5");
- list.add("cdef");
- list.add("123");
- list.add("343cdef");
- list.add("zf2");
- list.add("zf1");
- sop(list);
- Collections.sort(list,new StrLenComparator());
- sop(list);
- }
- }
- class StrLenComparator implements Comparator<String>{
- public int compare(String s1,String s2){
- if(s1.length()>s2.length())
- return 1;
- else if(s1.length()<s2.length())
- return -1;
- <font color="red"> return s1.compareTo(s2); //问题在此处</font>
- }
- }
复制代码
为什么把s1.compareTo(s2)改为s2.compareTo(s1)就能把相同长度的字符串逆序排列?
|