温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在 Java 中正确初始化集合类

发布时间:2025-02-08 05:51:41 来源:亿速云 阅读:144 作者:小樊 栏目:编程语言

在Java中,正确初始化集合类的方法取决于您要使用的集合类型

  1. ArrayList:
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> arrayList = new ArrayList<>();
        // 或者使用
        // List<String> arrayList = new ArrayList<String>();

        arrayList.add("元素1");
        arrayList.add("元素2");
        arrayList.add("元素3");

        System.out.println("ArrayList的内容: " + arrayList);
    }
}
  1. LinkedList:
import java.util.LinkedList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> linkedList = new LinkedList<>();
        // 或者使用
        // List<String> linkedList = new LinkedList<String>();

        linkedList.add("元素1");
        linkedList.add("元素2");
        linkedList.add("元素3");

        System.out.println("LinkedList的内容: " + linkedList);
    }
}
  1. HashSet:
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<String> hashSet = new HashSet<>();
        // 或者使用
        // Set<String> hashSet = new HashSet<String>();

        hashSet.add("元素1");
        hashSet.add("元素2");
        hashSet.add("元素3");
        hashSet.add("元素1"); // 重复元素,不会被添加到集合中

        System.out.println("HashSet的内容: " + hashSet);
    }
}
  1. TreeSet:
import java.util.TreeSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<String> treeSet = new TreeSet<>();
        // 或者使用
        // Set<String> treeSet = new TreeSet<String>();

        treeSet.add("元素1");
        treeSet.add("元素2");
        treeSet.add("元素3");

        System.out.println("TreeSet的内容: " + treeSet);
    }
}
  1. HashMap:
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> hashMap = new HashMap<>();
        // 或者使用
        // Map<String, Integer> hashMap = new HashMap<String, Integer>();

        hashMap.put("元素1", 1);
        hashMap.put("元素2", 2);
        hashMap.put("元素3", 3);

        System.out.println("HashMap的内容: " + hashMap);
    }
}
  1. TreeMap:
import java.util.TreeMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> treeMap = new TreeMap<>();
        // 或者使用
        // Map<String, Integer> treeMap = new TreeMap<String, Integer>();

        treeMap.put("元素1", 1);
        treeMap.put("元素2", 2);
        treeMap.put("元素3", 3);

        System.out.println("TreeMap的内容: " + treeMap);
    }
}

注意:在使用泛型时,最好指定集合中元素的类型,这样可以避免编译器警告并提高代码的可读性。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI