Java's JDK9 to add a set of optimization

  Typically, creating a set (e.g., in the code List or the Set ), and fill it with some elements directly. Examples of collection, several add method calls, such that the code repeats.

  9 the Java , add a collection of several factory method , it is more convenient to create a small number of elements of the set, the Map instance. New List , the Set , the Map static factory method makes it easier to create immutable instance of the collection.

   JDK9 new features:

     List interface, Set interfaces, Map Interface: inside adds a static method of, you can add multiple elements to the collection

 static <E> List<E> of​(E... elements)

    

    Use premise: Used when the number stored in the collection of elements has been determined, is not changed

  Note :  

    1. of the method is only applicable to List interface, Set Interface, Map interface, not the implementation class interface for receiving

    2. of the return value of the method can not be changed is a set of collections can not be reused add, put add an element, will be thrown

    3. Set the interface and the Map interfaces when the call of the method, can not have duplicate elements, otherwise it will throw an exception

   Demo:

 1  public static void main(String[] args) {
 2         List<String> list = List.of("a", "b", "a", "c", "d");
 3         System.out.println(list);//[a, b, a, c, d]
 4         //list.add("w");//UnsupportedOperationException:不支持操作异常
 5 
 6         //Set<String> set = Set.of("a", "b", "a", "c", "d");//IllegalArgumentException:非法参数异常,有重复的元素
 7         Set<String> set = Set.of("a", "b", "c", "d");
 8         System.out.println(set);
 9         //set.add("w");//UnsupportedOperationException: operation exception not supported
 10  
. 11          // the Map <String, Integer> Map.of Map = ( "San", 18 "John Doe", 19, "Wang Wu," 20, "San", 19) ; //// an IllegalArgumentException: illegal argument exception, duplicate elements 
12 is          the Map <String, Integer> Map.of Map = ( "San", 18 "John Doe", 19, "Wang Wu", 20 );
 13 is          System.out.println (Map); // {Wang Wu = 20, 19 = John Doe, 18 is Zhang} =
 14          // map.put ( "Zhao Si", 30); // an UnsupportedOperationException: operation not supported abnormal 
15      }

 

Guess you like

Origin www.cnblogs.com/niujifei/p/11443990.html