泛型与容器(3)——Set和Map

来源:互联网 发布:u盘芯片检测软件 编辑:程序博客网 时间:2024/05/15 13:01
Set
    Set不保存重复的元素。Set最常被使用的是测试归属性,你可以很容易地询问某个对象是否在某个Set中,因此,查找就成为了Set中最重要的操作,通常会选择实现HashSet,它专门对快速查找进行了优化。
下面是使用存放Integer对象的HashSet的示例:

public class SetOfInteger {public static void main(String[] args) {Random rand = new Random(47);Set<Integer> intset = new HashSet<Integer>(); // 无序// SortedSet<Integer> intset = new TreeSet<Integer>(); // 有序for (int i = 0; i < 10000; i++)intset.add(rand.nextInt(30));System.out.print(intset);}}

运行结果:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18, 21, 20, 23, 22, 25, 24, 27, 26, 29, 28]


使用contains()测试Set的归属性

//Set的一般操作public class SetOperations {public static void main(String[] args) {Set<String> set1 = new HashSet<String>();Collections.addAll(set1, "A B C D E F G H I J K L".split(" "));set1.add("M");System.out.println("H:" + set1.contains("H"));System.out.println("H:" + set1.contains("N"));Set<String> set2 = new HashSet<String>();Collections.addAll(set2, "H I J K L".split(" "));System.out.println("set2 in set1:" + set1.containsAll(set2));set1.remove("H");System.out.println("set1:" + set1);System.out.println("set2 in set1:" + set1.containsAll(set2));set1.removeAll(set2);System.out.println("set2 remove from set1:" + set1);Collections.addAll(set1, "X Y Z".split(" "));System.out.println("after add in set1:" + set1);}}

运行结果:

H:trueH:falseset2 in set1:trueset1:[D, E, F, G, A, B, C, L, M, I, J, K]set2 in set1:falseset2 remove from set1:[D, E, F, G, A, B, C, M]after add in set1:[D, E, F, G, A, B, C, M, Y, X, Z]


Map
    使用containsKey()containsValue()方法测试一个Map,查看它是否包含某个键或某个值。

//用Map的containsKey()和containsValue()方法测试是否包含该键或值public class PetMap {public static void main(String[] args) {Map<Integer, String> petMap = new HashMap<Integer, String>();petMap.put(1, "apple");petMap.put(2, "orange");petMap.put(3, "banana");System.out.println(petMap);String num = petMap.get(2);System.out.println(num);System.out.println(petMap.containsKey(3));System.out.println(petMap.containsValue("apple"));}}

运行结果:

{1=apple, 2=orange, 3=banana}orangetruetrue

    KeySet()方法产生了某个对象所有键组成的Set。

0 0
原创粉丝点击