温馨提示×

java集合怎么创建

小亿
142
2024-01-17 07:18:47
栏目: 编程语言

Java集合可以通过以下几种方式进行创建:

  1. 使用new关键字创建集合对象:

    List<Integer> list = new ArrayList<>();
    Set<String> set = new HashSet<>();
    Map<String, Integer> map = new HashMap<>();
    
  2. 使用集合工具类创建集合对象:

    List<Integer> list = Arrays.asList(1, 2, 3);
    Set<String> set = new HashSet<>(Arrays.asList("a", "b", "c"));
    Map<String, Integer> map = new HashMap<>(Map.of("key1", 1, "key2", 2));
    
  3. 使用集合工厂方法创建集合对象:

    List<Integer> list = List.of(1, 2, 3);
    Set<String> set = Set.of("a", "b", "c");
    Map<String, Integer> map = Map.of("key1", 1, "key2", 2);
    

注意:集合对象创建后,可以根据需要进行添加、删除、修改等操作。

0