程序代码:
package homework09.homework0926;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Demo004 {
public static void main(String[] args) {
List list = new ArrayList();
list.add("one");
list.add("two");
list.add("three");
list.add("four");
list.add(1,"9");
System.out.println(list);
list.set(2, "6");
System.out.println(list);
Object object = list.remove(2);
System.out.println(object);
System.out.println(list);
Object obj = list.get(0);
System.out.println(obj);
list.sort(new StringComparator());
System.out.println(list);
}
}
class StringComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof String && o2 instanceof String){
String str1 = (String)o1;
String str2 = (String)o2;
return str1.length()-str2.length();
}
return 0;
}
}
代码运行结果: