java之hashSet
1 import java.util.HashSet; 2 import java.util.Set; 3 4 5 public class demo { 6 public static void main(String[] args) { 7 Set<Test> set = new HashSet<Test>(); 8 Test test = new Test(); 9 10 test.setStr("123"); 11 set.add(test); 12 System.out.println(set); 13 14 test.setStr("456"); 15 set.add(test); 16 System.out.println(set); 17 18 test.setStr("789"); 19 set.add(test); 20 System.out.println(set); 21 } 22 } 23 class Test{ 24 String str; 25 26 public void setStr(String str) { 27 this.str = str; 28 } 29 30 @Override 31 public String toString() { 32 return str; 33 } 34 35 @Override 36 public int hashCode() { 37 return str.hashCode(); 38 } 39 40 }
这段代码将会输出
[123]
[456, 456]
[789, 789, 789]
所以java的集合加入的是引用,大概是为了节约时间吧
如果要插入对象,就应该不断创建对象的引用
1 import java.util.HashSet; 2 import java.util.Set; 3 4 5 public class demo { 6 public static void main(String[] args) { 7 Set<Test> set = new HashSet<Test>(); 8 Test test = new Test(); 9 10 test.setStr("123"); 11 set.add(test); 12 System.out.println(set); 13 14 test = new Test(); 15 test.setStr("456"); 16 set.add(test); 17 System.out.println(set); 18 19 test = new Test(); 20 test.setStr("789"); 21 set.add(test); 22 System.out.println(set); 23 } 24 } 25 class Test{ 26 String str; 27 28 public void setStr(String str) { 29 this.str = str; 30 } 31 32 @Override 33 public String toString() { 34 return str; 35 } 36 37 @Override 38 public int hashCode() { 39 return str.hashCode(); 40 } 41 42 }
[123]
[123, 456]
[123, 456, 789]