Kev*_*edi 2 java string hashset
首先在HashSet中添加元素并打印HashSet的大小,该大小按预期返回.但我修改了一个对象值并再次存储到HashSet并使用对象名称删除对象.但我仍然和以前一样大小.我的代码如下:
public class Test {
private String s;
public Test(String s){
this.s = s ;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Object> hs = new HashSet<Object>();
Test t1 = new Test("Keval");
Test t2 = new Test("Keval");
String s1 = new String("Keval");
hs.add(t1);
hs.add(t2);
hs.add(s1);
System.out.println("Set Size :: " + hs.size());
s1 = new String("Demo");
hs.remove(s1);
System.out.println("Set Size :: " + hs.size());
}
}
Run Code Online (Sandbox Code Playgroud)
上述代码的输出是:
Set Size :: 3
Set Size :: 3 // Why it prints 3 insted of 2???
Run Code Online (Sandbox Code Playgroud)
String s1 = new String("Keval");
....
hs.add(s1);
....
s1 = new String("Demo");
hs.remove(s1);
Run Code Online (Sandbox Code Playgroud)
你正在添加一个String等于String"Keval"的东西HashSet,但是你试图从中移除一个String等于String"Demo"的东西Set.
您的HashSet包含不String等于"Demo",因此该remove()调用不会删除任何内容Set,也不会影响其大小.
当你删除该s1 = new String("Demo")行时,s1仍然引用 String添加到Set(等于"Keval"的hs.remove(s1)那个)的行,所以String从中移除它Set.
| 归档时间: |
|
| 查看次数: |
17204 次 |
| 最近记录: |