第一题:
1 package zuoye; 2 import java.util.*; 3 public class SetandList { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 8 List<String> list=new ArrayList<String>(); 9 list.add("A"); 10 if(list.add("a")) 11 { 12 System.out.println("添加“a”成功"); 13 } 14 list.add("c"); 15 list.add("C"); 16 17 if(!list.add("a")) 18 { 19 System.out.println("添加“a”失败"); 20 } 21 else 22 { 23 System.out.println("添加“a”成功"); 24 } 25 list.add("a"); 26 Set<String> s=new HashSet<String>(); 27 s.add("A"); 28 if(s.add("a")) 29 { 30 System.out.println("保存a成功"); 31 } 32 s.add("c"); 33 s.add("C"); 34 if(!s.add("a")) 35 { 36 System.out.println("保存a失败"); 37 } 38 s.add("a"); 39 40 } 41 42 }
第二题:
Emp类代码:
1 package zuoye; 2 3 public class Emp { 4 private String id; 5 private String name; 6 public String getId() { 7 return id; 8 } 9 public void setId(String id) { 10 this.id = id; 11 } 12 public String getName() { 13 return name; 14 } 15 public void setName(String name) { 16 this.name = name; 17 } 18 public Emp(String id, String name) { 19 this.id = id; 20 this.name = name; 21 } 22 23 24 }
Test类代码:
1 package zuoye; 2 import java.util.*; 3 public class Zuoye { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 Map map=new HashMap(); 8 Emp emp=new Emp("001","张全蛋"); 9 Emp emp1=new Emp("002","李狗蛋"); 10 Emp emp2=new Emp("003","王二麻子"); 11 Emp emp3=new Emp("004","赵铁柱"); 12 Emp emp4=new Emp("005","刘能"); 13 map.put(emp.getId(), emp.getName()); 14 map.put(emp1.getId(), emp1.getName()); 15 map.put(emp2.getId(), emp2.getName()); 16 map.put(emp3.getId(), emp3.getName()); 17 map.put(emp4.getId(), emp4.getName()); 18 Set set=map.keySet(); 19 Iterator it=set.iterator(); 20 System.out.println("移除id为005之前:"); 21 while(it.hasNext()) 22 { 23 String str=(String)it.next(); 24 String name=(String)map.get(str); 25 System.out.println(str+""+name); 26 27 } 28 map.remove("005"); 29 Iterator iter=set.iterator(); 30 map.remove(emp4); 31 System.out.println("移除id为005之后:"); 32 while(iter.hasNext()) 33 { 34 map.remove(emp4); 35 String str=(String)iter.next(); 36 String name=(String)map.get(str); 37 System.out.println(str+""+name); 38 } 39 40 } 41 42 }