java 集合类工具函数


下面的代码主要调用工具类的2个常用函数,singletonList和emptyList

	 String[] init = { "One", "Two", "Three", "One", "Two", "Three" };
	 List list = new ArrayList(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);

他们返回的list是不可变的。singletonList只有一个元素而且是final

    private static class SingletonList
	extends AbstractList
	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;
        }
    }


对于emptyList


  public static final List EMPTY_LIST = new EmptyList();


就是创建了一个final的空list。至于实现看下面的代码:

    private static class EmptyList
	extends AbstractList
	implements RandomAccess, Serializable {
	// use serialVersionUID from JDK 1.2.2 for interoperability
	private 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,java,arraylist)