The following code mainly calls 2 common functions of the tool class, Singletonlist and Emptylist
String[] init = {"One", "one", "three", "one", "one", "three"}; List List = new arraylist<string> (arrays.aslist (init)); SYSTEM.OUT.PRINTLN (list); List.add ("Eee"); SYSTEM.OUT.PRINTLN (list); List = Collections.singletonlist ("one"); SYSTEM.OUT.PRINTLN (list);//List.add ("eee");//System.out.println ("End"); List = Collections.emptylist (); List.add ("Eee"); SYSTEM.OUT.PRINTLN (list);
The list that they return is immutable. Singletonlist has only one element and is final.
private static Class Singletonlist<e>extends abstractlist<e>implements randomaccess, Serializable { Static final Long serialversionuid = 3093736618740652951L; Private final E element; Singletonlist (E obj) {element = obj;} public int size () {return 1;} Public Boolean contains (Object obj) {return eq (obj, Element);} Public E get (int index) { if (index! = 0) throw new Indexoutofboundsexception ("Index:" +index+ ", size:1"); return element; } }
For Emptylist
public static final List empty_list = new Emptylist ();
is to create a final empty list. As for the implementation look at the following code:
private static Class Emptylistextends abstractlist<object>implements randomaccess, Serializable {//Use Serialversionuid from JDK 1.2.2 for interoperabilityprivate static final long Serialversionuid = 8842843931221139166l;
public int size () {return 0;} Public Boolean contains (Object obj) {return false;} Public Object get (int index) { throw new Indexoutofboundsexception ("index:" +index); } Preserves Singleton property private Object readresolve () { return empty_list; } }
Java Collection Class tool functions