运行结果: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]
运行结果://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:true H:false set2 in set1:true set1:[D, E, F, G, A, B, C, L, M, I, J, K] set2 in set1:false set2 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()方法测试是否包含该键或值 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")); } }
KeySet()方法产生了某个对象所有键组成的Set。{1=apple, 2=orange, 3=banana} orange true true