Java Collection Class tool functions

Source: Internet
Author: User


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.