
工厂方法是一种特殊类型的静态方法,可以用于创建不可修改的集合实例。这意味着我们可以使用这些方法来创建包含少量元素的列表、集合和映射。
List.of()
List.of()是一个静态工厂方法,提供了一种便捷的方式来创建不可变的列表。
语法
<strong>List.of(elements...)</strong>
Example
import java.util.List;
public class ListTest {
public static void main(String[] args) {
<strong>List<String></strong> list =<strong> List.of</strong>("item 1", "item 2", "item 3", "item 4", "item 5");
for(String l : list) {
System.out.println(l);
}
}
}输出
<strong>item 1 item 2 item 3 item 4 item 5</strong>
Set.of() 方法
Set.of() 是一个静态工厂方法,提供了一种方便的方式来创建不可变的集合。
语法
<strong>Set.of(elements...) </strong>
Example
import java.util.Set;
public class SetTest {
public static void main(String[] args) {
<strong>Set<String></strong> set = <strong>Set.of</strong>("Item 1", "Item 2", "Item 3", "Item 4", "Item 5");
for(String s : set) {
System.out.println(s);
}
}
}输出
<strong>Item 5 Item 1 Item 2 Item 3 Item 4</strong>
Map.of() 和 Map.ofEntries() 方法
The Map.of() 和 Map.ofEntries() 是静态工厂方法,提供了一种方便的方式来创建不可变的 映射。
Syntax
<strong>Map.of(k1, v1, k2, v2) Map.ofEntries(entry(k1, v1), entry(k2, v2),...)</strong>
Example
import java.util.Map;
public class MapTest {
public static void main(String[] args) {
<strong>Map<Integer, String></strong> map = <strong>Map.of</strong>(101, "Raja", 102, "Adithya", 103, "Jai");
for(<strong>Map.Entry<Integer, String></strong> m : map.<strong>entrySet()</strong>) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}Output
<strong>103 Jai 102 Adithya 101 Raja</strong>











