如何从HashSet中移除一个元素?

huangapple go评论76阅读模式
英文:

How to Remove an element from HashSet?

问题

我想从一个HashSet中删除一个元素。
有人可以帮助我理解,为什么无法从这个HashSet中删除“emma”猫?
可能的最佳解决方案是什么?

谢谢!

public static void main(String[] args) {

    HashSet<Cat> set = new HashSet<Cat>();

    set.add(new Cat("cindy"));
    set.add(new Cat("emma"));

    Iterator<Cat> iterator = set.iterator();

    while (iterator.hasNext()) {
        Cat name1 = iterator.next();

        if (name1.equals("emma")) {
            iterator.remove();
        }
    }
    System.out.println(set);
}

public static class Cat {
    private String name;

    public Cat(String name) {
        this.name = name;
    }

    public String toString() {
        return this.name;
    }
}
英文:

I want to remove an element from a HashSet.
Can sb help me to understand, why cat "emma" cant be removed from this HashSet?
What could be the best solution?

Thank you!

public static void main(String[] args) {

	HashSet&lt;Cat&gt; set = new HashSet&lt;Cat&gt;();
	
	set.add(new Cat(&quot;cindy&quot;));
	set.add(new Cat(&quot;emma&quot;));
	
	Iterator&lt;Cat&gt; iterator = set.iterator();

	while (iterator.hasNext()) {
		Cat name1 = iterator.next();

		if (name1.equals(&quot;emma&quot;)) {
			iterator.remove();
		}
	}
	System.out.println(set);
}

public static class Cat {
	private String name;

	public Cat(String name) {
		this.name = name;
	}

	public String toString() {
		return this.name;
	}
}

答案1

得分: 1

你正在使用equals方法将字符串作为参数传递给Cat的方法,该方法将返回false。你可以使用已重写的toString方法,或者为名称设置一个getter方法,并将其与字符串进行比较。

英文:

You are using the equals method of a Cat with a string as an argument, which returns false. You can use the toString method as you have overridden it, or have a getter for the name and compare it with the string.

答案2

得分: 1

boolean equals(Object anObject)

请注意,`equals` 方法接受 `Objects`,因此当两个变量不是您期望的 `String` 类型时不会引发异常顺便说一下IntelliJ IDEA 会为此情况提供检查)。您只需要将 `String "emma"``name1.name` 进行比较即可

while (it.hasNext()) {
    Cat name1 = it.next();

    if ("emma".equals(name1.toString()))
        it.remove();
}
英文:
boolean equals(Object anObject)

Pay attention, that equals method accepts Objects, so you do not get an exception when two variables are not String as you expect (by the way, IntelliJ IDEA gives you an inspection for this case). All you need to fix it is to compare String &quot;emma&quot; with name1.name:

while (it.hasNext()) {
    Cat name1 = it.next();

    if (&quot;emma&quot;.equals(name1.toString()))
        it.remove();
}

答案3

得分: 0

你可以通过以下代码来查看你的问题:

Cat c = new Cat("emma");
if(c.equals("emma"))
    System.out.println("true"); // 这是你期望的结果
else
    System.out.println("false!"); // 这是实际发生的事情!

这是因为如果没有定义equals方法,默认情况下它会比较两个对象是否完全相同。你可以在这里12找到有关此行为的更多信息。在你的情况下,你正在比较一个String对象和一个Cat对象。

一个可能的解决方案是使用你在类中定义的toString方法来比较字符串之间的差异。equals方法在String类中被重写,具有你期望的行为。

public static void main(String[] args) {
    HashSet<Cat> set = new HashSet<Cat>();
    
    set.add(new Cat("cindy"));
    set.add(new Cat("emma"));
    
    Iterator<Cat> iterator = set.iterator();

    while (iterator.hasNext()) {
        Cat name1 = iterator.next();

        if (name1.toString().equals("emma")) {
            iterator.remove();
        }
    }
    System.out.println(set);
}

另一个解决方案是在你的Cat类中重写equals方法。以下是你可以这样做的一种方式:

import java.util.*;

class Cat {
    private String name;

    public Cat(String name) {
        this.name = name;
    }

    public String toString() {
        return this.name;
    }

    public Boolean equals(Cat other) {
        return this.name.equals(other.name);
    }
}

public class Test {
    public static void main(String[] args) {
        HashSet<Cat> set = new HashSet<Cat>();
        
        Cat cindy = new Cat("cindy");
        Cat emma = new Cat("emma");

        set.add(cindy);
        set.add(emma);
        
        Iterator<Cat> iterator = set.iterator();

        while (iterator.hasNext()) {
            Cat cat = iterator.next();

            if (cat.equals(emma)) {
                iterator.remove();
            }
        }
        System.out.println(set);
    }
}
英文:

You can see your problem running the following code:

Cat c = new Cat(&quot;emma&quot;);
if(c.equals(&quot;emma&quot;))
    System.out.println(&quot;true&quot;); // this is what you expect
else
    System.out.println(&quot;false!&quot;); // this is what actually happens!

This is because if the equals method is not defined, by default it compares that the two objects are exactly the same. You can find more information about this behavior here and here. In your case you are comparing a String object with a Cat object.

One possible solution would be to use the toString method you hava defined in your class to compare between strings. The equals method is overridden in the String class to have the behavior you expect.

public static void main(String[] args) {

    HashSet&lt;Cat&gt; set = new HashSet&lt;Cat&gt;();
    
    set.add(new Cat(&quot;cindy&quot;));
    set.add(new Cat(&quot;emma&quot;));
    
    Iterator&lt;Cat&gt; iterator = set.iterator();

    while (iterator.hasNext()) {
        Cat name1 = iterator.next();

        if (name1.toString().equals(&quot;emma&quot;)) {
            iterator.remove();
        }
    }
    System.out.println(set);
}

Another solution could be to override the equals method in your cat class. Here is a way you could do it:

import java.util.*;

class Cat {
    private String name;

    public Cat(String name) {
        this.name = name;
    }

    public String toString() {
        return this.name;
    }

    public Boolean equals(Cat other) {
        return this.name.equals(other.name);
    }
}
public class Test {
public static void main(String[] args) {
    HashSet&lt;Cat&gt; set = new HashSet&lt;Cat&gt;();
    
    Cat cindy = new Cat(&quot;cindy&quot;);
    Cat emma = new Cat(&quot;emma&quot;);

    set.add(cindy);
    set.add(emma);
    
    Iterator&lt;Cat&gt; iterator = set.iterator();

    while (iterator.hasNext()) {
        Cat cat = iterator.next();

        if (cat.equals(emma)) {
            iterator.remove();
        }
    }
    System.out.println(set);
    }
}

huangapple
  • 本文由 发表于 2020年9月16日 16:08:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63915740.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定