从HashSet中删除元素

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)

Era*_*ran 8

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.

  • @KevalTrivedi你添加到你的集合`new String("Keval");`但是试图删除`new String("Demo");`它们不是相同的对象.换句话说,您正在尝试删除集合中不存在的对象. (2认同)
  • @KevalTrivedi它可能甚至没有运行`equals`方法,因为`hashCode`很可能是不同的,所以这两个字符串可能映射到不同的桶. (2认同)