Java 9 集合工厂方法

Java 教程 · 2019-02-09 20:59:46

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); } }

执行输出结果为:

[A, B, C]
[A, B, C]
{A=Apple, B=Boy, C=Cat}

新方法创建集合

Java 9 中,以下方法被添加到 List,Set 和 Map 接口以及它们的重载对象。

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 和 Set 接口, of(...) 方法重载了 0 ~ 10 个参数的不同方法 。

  • Map 接口, of(...) 方法重载了 0 ~ 10 个参数的不同方法 。

  • Map 接口如果超过 10 个参数, 可以使用 ofEntries(...) 方法。

新方法创建集合

实例

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); } }

输出结果为:

[A, B, C]
[A, B, C]
{A=Apple, B=Boy, C=Cat}
{A=Apple, B=Boy, C=Cat}

点击查看所有 Java 教程 文章: https://codercto.com/courses/l/12.html

查看所有标签

Flow-Based Programming (2nd Edition)

Flow-Based Programming (2nd Edition)

CreateSpace / 2010-5-14 / $69.95

Written by a pioneer in the field, this is a thorough guide to the cost- and time-saving advantages of Flow-Based Programming. It explains the theoretical underpinnings and application of this program......一起来看看 《Flow-Based Programming (2nd Edition)》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试