1 public final class ThreeStooges { 2 3 4 /* 5 * stooges是Set<String>类型的引用,final限定该引用成员属性stooges被赋初值后,就不能再改变去引用其他的同类对象 6 * final只是限定了声明的引用stooges不能改变,stooges引用的对象能不能改变,由被引用对象本身的类定义来决定 7 */ 8 private final Set<String> stooges = new HashSet<String>(); 9 10 public ThreeStooges() { 11 stooges.add("Moe"); 12 stooges.add("Larry"); 13 stooges.add("Curly"); 14 15 //stooges = new HashSet<String>(); //The final field ThreeStooges.stooges cannot be assigned 16 } 17 18 /** 19 * 向被引用的HashSet中添加一个元素 20 * final域stooges仍引用着赋初值时的那个HashSet对象,而stooges.add(name);只是向被引用的被引用的HashSet中添加一个元素 21 * @param name 22 */ 23 public void add(String name) { 24 stooges.add(name); 25 } 26 27 28 public boolean isStooge(String name) { 29 return stooges.contains(name); 30 } 31 32 33 public void print() { 34 Iterator<String> iterator = stooges.iterator(); 35 while (iterator.hasNext()) { 36 System.out.println(iterator.next() + ", "); 37 } 38 } 39 40 41 public static void main(String[] args) { 42 43 44 ThreeStooges ts = new ThreeStooges(); 45 ts.add("asn"); 46 ts.print(); 47 } 48 }
输出:
Moe,
asn,
Curly,
Larry,