05_Iterator

 1 import java.util.*;
 2 
 3 class Name
 4 {
 5     private String firstName,lastName;
 6     
 7     public String getFirstName() {
 8         return firstName;
 9     }
10 
11     public void setFirstName(String firstName) {
12         this.firstName = firstName;
13     }
14 
15     public String getLastName() {
16         return lastName;
17     }
18 
19     public void setLastName(String lastName) {
20         this.lastName = lastName;
21     }
22     public Name(String firstName,String lastName)
23     {
24         this.firstName=firstName;
25         this.lastName=lastName;        
26     }
27     public boolean equals(Object obj)
28     {
29         if (obj instanceof Name)
30         {
31             Name name=(Name)obj;
32             return (firstName.equals(name.firstName)) && (lastName.equals(name.lastName));            
33         }
34         
35         return super.equals(obj);
36     }
37     public int hashCode()
38     {
39         return firstName.hashCode();
40     }
41     public String toString() {  return firstName + " " + lastName;  }    
42     
43 }
44 
45 
46 
47 public class testmy1 {
48     
49     public static void main(String[] args) 
50     {
51         Collection c = new HashSet();
52         c.add(new Name("f1","l1"));
53         c.add(new Name("f2","l2"));
54         c.add(new Name("f3","l3"));
55         c.add(new Name("f33","l33"));
56         
57         Iterator i=c.iterator();
58         while (i.hasNext())
59         {
60             Name n=(Name)i.next();
61             System.out.print(n.getFirstName()+" ");
62         }
63 
64         i=c.iterator();
65         while (i.hasNext())
66         {
67             Name n=(Name)i.next();
68             if (n.getFirstName().length()==3)
69             {
70                 i.remove();
71             }
72         }
73         System.out.println(c);
74     }
75 
76 }
原文地址:https://www.cnblogs.com/delphione/p/3001957.html