English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java 9 在List,Set 和 Map 接口中,新的静态工厂方法可以创建这些集合的不可变示例。
这些工厂方法可以以更简洁的方式来创建集合。
旧方法创建集合
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class Tester { public static void main(String []args) { Set<String> set = new HashSet<>(); set.add("A"); set.add("B"); set.add("C"); set = Collections.unmodifiableSet(set); System.out.println(set); List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list = Collections.unmodifiableList(list); System.out.println(list); Map<String, String> map = new HashMap<>(); map.put("A","Apple"); map.put("B","Boy"); map.put("C","Cat"); map = Collections.unmodifiableMap(map); System.out.println(map); } }
Die Ausgabe des Ausführungsresultats ist:
[A, B, C] [A, B, C] {A=Apple, B=Boy, C=Cat}
Der neue Methode, eine Sammlung zu erstellen
Java 9 In der folgenden Methode wurde eine Methode zu List, Set und Map-Interface sowie ihren Übersetzungsobjekten hinzugefügt.
static <E> List<E> of(E e1, E e2, E e3); static <E> Set<E> of(E e1, E e2, E e3); static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3); static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)
List und Set-Interface, die Methode of(...) ist 0 ~ 10 Parameter vorhanden sind.
Map-Interface, die Methode of(...) ist 0 ~ 10 Parameter vorhanden sind.
unterschiedliche Methoden des Map-Interfaces, wenn mehr als 10 Parameter können mit der Methode ofEntries(...) verwendet werden.
Der neue Methode, eine Sammlung zu erstellen
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.AbstractMap; import java.util.Map; import java.util.Set; public class Tester { public static void main(String []args) { Set<String> set = Set.of("A", "B", "C"); System.out.println(set); List<String> list = List.of("A", "B", "C"); System.out.println(list); Map<String, String> map = Map.of("A","Apple","B","Boy","C","Cat"); System.out.println(map); Map<String, String> map1 = Map.ofEntries ( new AbstractMap.SimpleEntry<>("A","Apple"), new AbstractMap.SimpleEntry<>("B","Boy"), new AbstractMap.SimpleEntry<>("C","Cat")); System.out.println(map1); } }
Die Ausgabe ist:
[A, B, C] [A, B, C] {A=Apple, B=Boy, C=Cat} {A=Apple, B=Boy, C=Cat}