Collection和Map类图预览与比较

时间:2021-01-18 02:58:29

类图

Collection和Map类图预览与比较

HashSet和TreeSet的区别:https://www.cnblogs.com/bobi1234/p/10759769.html
HashSet和LinkedHashSet区别:https://www.cnblogs.com/bobi1234/p/10759775.html

ArrayList和Vector的区别:https://www.cnblogs.com/bobi1234/p/10759767.html
ArrayList和LinkedList的区别:https://www.cnblogs.com/bobi1234/p/10759765.html

Collection和Map类图预览与比较

HashMap和Hashtable的区别:https://www.cnblogs.com/bobi1234/p/10759778.html
HashMap和TreeMap的区别:https://www.cnblogs.com/bobi1234/p/10759779.html
HashMap与ConcurrentHashMap的区别:https://www.cnblogs.com/bobi1234/p/10759800.html
HashMap和LinkedHashMap的区别:https://www.cnblogs.com/bobi1234/p/10759823.html

List数据是否可重复、可为空、可为null

public class ListDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("11");
        list.add("22");
        list.add("33");
        list.add("11");
        list.add("");
        list.add(null);
        System.out.println(list);
        List<String> list2 = new LinkedList<>();
        list2.add("11");
        list2.add("22");
        list2.add("33");
        list2.add("11");
        list2.add("");
        list2.add(null);
        System.out.println(list2);
    }
}
[11, 22, 33, 11, , null]
[11, 22, 33, 11, , null]
结论:ArrayList和LinkedList的值可重复、可为空、可为null

Set数据是否可重复、可为空、可为null

public class SetDemo {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("11");
        set.add("22");
        set.add("33");
        set.add("11");
        set.add("");
        set.add(null);
        System.out.println(set);
        Set<String> set2 = new LinkedHashSet<>();
        set2.add("11");
        set2.add("22");
        set2.add("33");
        set2.add("11");
        set2.add("");
        set2.add(null);
        System.out.println(set2);
    }
}
[11, 22, 33, , null]
[11, 22, 33, , null]
结论:HashSet和LinkedHashSet的值不能重复,但可为空,可为null

Map数据是否可重复、可为空、可为null

public class MapDemo {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("语文", 100);
        map.put("数学", 99);
        map.put("语文", 98);
        map.put("", 97);
        map.put(null, 96);
        map.put(null, null);
        System.out.println(map);
        Map<String, Integer> map2 = new TreeMap<>();
        map2.put("语文", 100);
        map2.put("数学", 99);
        map2.put("语文", 98);
        map2.put("", 97);
        map2.put("外语", null);
        // map2.put(null, 96);   NullPointerException
        // map2.put(null, null); NullPointerException
        System.out.println(map2);
    }
}
{=97, null=null, 数学=99, 语文=98}
{=97, 外语=null, 数学=99, 语文=98}
结论:
HashMap的key不可重复,但可为空、可为null,value不做讨论。
TreeMap的key不可重复、不可为null,但可为空,value不做讨论。