jdk9增加集合工厂方法

152 阅读2分钟

前言

Jdk9引入了一些改进的集合工厂方法,使用创建和初始化集合对象更加方便

集合方法使用

List.of()

使用List.of()可以快速创建一个List集合

public class ListDemo {

    public static void main(String[] args) {
        List<Integer> list = List.of(1, 2, 3, 4, 5, 6);
        System.out.println(list);
    }
}

但是List.of()是一个不可变集合,如果添加或者移除就会报错

import java.util.List;

public class ListDemo {

    public static void main(String[] args) {
        List<Integer> list = List.of(1, 2, 3, 4, 5, 6);
        System.out.println(list);
        list.add(1);
        System.out.println(list);
    }
}

输出结果如下图

image.png 而且List.of()不能添加null对象,否则会报错

import java.util.List;

public class ListDemo {

    public static void main(String[] args) {
        List<Integer> list = List.of(1, null);
        System.out.println(list);
    }
}

image.png

Set.of()

使用Set.of()可以快速创建一个Set集合


import java.util.Set;

public class SetDemo {

    public static void main(String[] args) {
        Set<Integer> set = Set.of(1, 2, 3, 4, 5, 6);
        System.out.println(set);
    }
}

但是Set.of()是一个不可变集合,如果添加或者移除就会报错


import java.util.Set;

public class SetDemo {

    public static void main(String[] args) {
        Set<Integer> set = Set.of(1, 2, 3, 4, 5, 6);
        System.out.println(set);
        set.add(7);
        System.out.println(set);
    }
}

image.png 而且Set.of()不能添加null对象,否则会报错

public class SetDemo {

    public static void main(String[] args) {
        Set<Integer> set = Set.of(1, 2, 3, 4, 5, 6, null);
        System.out.println(set);
    }
}

输出结果如下

image.png

Map.of()

使用Map.of()可以快速创建一个Map集合

import java.util.Map;


public class MapDemo {

    public static void main(String[] args) {
        Map<Integer, Integer> map = Map.of(1, 2, 3, 4, 5, 6);
        System.out.println(map);
    }
}

输出结果如下 image.png 但是Map.of()是一个不可变集合,如果添加或者移除就会报错

import java.util.Map;


public class MapDemo {

    public static void main(String[] args) {
        Map<Integer, Integer> map = Map.of(1, 2, 3, 4, 5, 6);
        System.out.println(map);
        map.put(10, 10);
        System.out.println(map);
    }
}

输出结果如下

image.png 移除Map.of()元素

public class MapDemo {

    public static void main(String[] args) {
        Map<Integer, Integer> map = Map.of(1, 2);
        map.remove(1);
        System.out.println(map);
    }
}

image.png 而且Map.of()中的key和value不能为null对象,否则会报错

import java.util.Map;


public class MapDemo {

    public static void main(String[] args) {
        Map<Integer, Integer> map = Map.of(null, 1);
        System.out.println(map);
    }
}

输出结果如下

image.png


import java.util.Map;


public class MapDemo {

    public static void main(String[] args) {
        Map<Integer, Integer> map = Map.of(1, null);
        System.out.println(map);
    }
}

输出结果如下

image.png

总结

jdk9增加集合工厂方法,可以快速在开发中创建数组集合,合理使用它,可以加快开发效率