Set相关知识:
1 package org.hanqi.array; 2 3 import java.util.*; 4 5 public class Test2 { 6 7 public static void main(String[] args) { 8 9 // int i;//默认i=0 10 // int [] m = new int[5];//赋值了5个0 11 12 //哈希 13 Set<String> s = new HashSet<String>(); 14 HashSet<String> s1 = new HashSet<String>(); 15 16 if(s.add("a")) 17 { 18 System.out.println("保存a成功"); 19 } 20 s.add("b"); 21 s.add("c"); 22 s.add("d"); 23 s.add("e"); 24 s.add("f"); 25 s.add("g"); 26 27 if(!s.add("a")) 28 { 29 System.out.println("保存a失败"); 30 } 31 //s.add("a"); 32 //s.add("a"); 33 34 for(String t:s) 35 { 36 System.out.print(t); 37 } 38 39 System.out.println(); 40 41 System.out.println("s的size="+s.size()); 42 43 if(s.remove("d")) 44 { 45 System.out.println("移除成功"); 46 } 47 else 48 { 49 System.out.println("移除失败"); 50 } 51 52 System.out.println("s的size="+s.size()); 53 54 //迭代器 55 Iterator<String> it = s.iterator(); 56 while(it.hasNext()) 57 { 58 String t = it.next(); 59 if(t.equals("c")) 60 { 61 it.remove(); 62 } 63 else 64 { 65 System.out.print(t); 66 } 67 68 } 69 70 System.out.println(); 71 72 System.out.println("s的size="+s.size()); 73 74 System.out.println("TreeSet"); 75 76 Set<String> s2 = new TreeSet<String>(); 77 78 s2.add("f"); 79 s2.add("b"); 80 s2.add("d"); 81 s2.add("c"); 82 s2.add("e"); 83 s2.add("a"); 84 s2.add("g"); 85 86 for(String t:s2) 87 { 88 System.out.print(t); 89 } 90 91 System.out.println(); 92 93 System.out.println("s2的size="+s2.size()); 94 } 95 }
运行结果为:
Map相关知识:
1 package org.hanqi.array; 2 3 import java.util.*; 4 5 public class Test3 { 6 7 public static void main(String[] args) { 8 9 Map<String,String> m = new HashMap<String,String>(); 10 11 m.put("7", "淄博"); 12 m.put("9", "济南"); 13 m.put("5", "青岛"); 14 m.put("1", "青岛"); 15 m.put("8", "青岛"); 16 m.put("6", "青岛"); 17 m.put("3", "青岛"); 18 m.put("2", "青岛"); 19 m.put("0", "青岛"); 20 //长度 21 System.out.println("长度="+m.size()); 22 m.put("0534", "青岛"); 23 m.put(null, null); 24 System.out.println("长度="+m.size()); 25 //根据key获取value 26 System.out.println("0533="+m.get("0533")); 27 //key是否存在 28 if(m.containsKey("0533")) 29 { 30 System.out.println("key 0533已存在"); 31 } 32 //value是否存在 33 if(m.containsValue("淄博")) 34 { 35 System.out.println("value 淄博已存在"); 36 } 37 //遍历 38 for(String k:m.keySet()) 39 { 40 System.out.println(k+"="+m.get(k)); 41 } 42 } 43 }
运行结果为:
相关思维导图:
时间: 2024-10-05 04:32:24