import java.util.*;
class Pet {}
class Rat extends Pet{}
class Manx extends Pet{}
class Cymric extends Pet{}
class Mutt extends Pet{}
class Pug extends Pet{}
class Hamster extends Pet{}
class Mouse extends Pet{}
public class ListFeature {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Pet> pets =new ArrayList<Pet>( Arrays.asList(new Rat(), new Manx(), new Cymric(), new Mutt(), new Pug(), new Cymric(), new Pug()));
/*
* 此处不能够用
* List<Pet> pets =Arrays.asList(new Rat(), new Manx(), new Cymric(), new Mutt(), new Pug(), new Cymric(), new Pug());
* 否则会得到
* Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at ListFeature.main(ListFeature.java:30)
错误提醒,
* java.lang.UnsupportedOperationException是指请求的方法不被支持的异常。
* 在从Arrays.asList()转化过来的List的不支持add()和remove()方法,
* 这是由于从Arrays.asList()返回的是返回java.util.Arrays$ArrayList,而不是ArrayList。
* Arrays$ArrayList和ArrayList都是继承AbstractList,
* add() 和remove()等方法在AbstractList中默认throw UnsupportedOperationException而不做任何操作。
* ArrayList重写这些方法对List进行操作,而Arrays$ArrayList却没有重写add()和 remove()等方法,
* 所以对从Arrays.asList()转化过来的List进行add()和remove()会出现UnsupportedOperationException异常。
*/
System.out.println("1: " + pets);
Hamster h = new Hamster();
pets.add(h);
System.out.println("2: " + pets);
System.out.println("3: " + pets.contains(h));
Pet p = pets.get(2);
System.out.println("4: " + p + " " + pets.indexOf(p));
Pet cymric = new Cymric();
System.out.println("5: " + pets.indexOf(cymric));
System.out.println("6: " + pets.remove(cymric));
System.out.println("7: " + pets.remove(p));
/*当确定一个元素是否属于某个List, 发现某个元素的索引, 以及从某个List中移除一个元素时,都会用到equals()方法(它是Object的一部分)*/
System.out.println("8: " + pets);
pets.add(3, new Mouse());
System.out.println("9: " + pets);
List<Pet> sub = pets.subList(1, 4);
System.out.println("sublist: " + sub);
System.out.println("10: " + pets.containsAll(sub));
Collections.sort(pets);//出现了错误,还没有找到原因。
System.out.println("sorted sublist: " + sub);
}
}