如何在ArrayList中移除元素?

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

How to remove elements in ArrayList?

问题

import java.util.ArrayList;

class A {
    int value;

    public A(int newValue) {
        setValue(newValue);
    }

    public int getValue() {
        return value;
    }

    public void setValue(int newValue) {
        value = newValue;
    }
}

class B {
    ArrayList<A> valuesOfA = new ArrayList<>();

    valuesOfA.add(new A(5));
    System.out.println("Adding...");
    for (A value : valueOfA) {
        System.out.println(value); // prints the values added.
    }
    valuesOfA.remove(new A(5));
    System.out.println("Removed");
    for (A value : valueOfA) {
        System.out.println(value);
    }
}

Element has still not been removed. What is the solution for this?


<details>
<summary>英文:</summary>

Below is sample code. 

How to remove a specific element in ArrayList?

import java.util.ArrayList;

class A {
int value;

public A(int newValue) {
    setValue(newValue);
}

public int getValue() {
    return value;
}

public void setValue(int newValue) {
    value = newValue;
}

}

class B {

ArrayList &lt;A&gt; valuesOfA = new ArrayList&lt;&gt;();
valuesOfA.add(new A(5));
System.out.println(&quot;Adding...&quot;);
for (A value: valueOfA) {
    System.out.println(value); //prints the values added.
}
valuesOfA.remove(new A(5));
System.out.println(&quot;Removed&quot;);
for (A value: valueOfA) {
    System.out.println(value);
}

}

Element as still not been removed. What is the solution for this?

</details>


# 答案1
**得分**: 1

重新定义 Class A 如下:

```java
class A {
    private int value;

    public A(int newValue) {
        setValue(newValue);
    }

    public int getValue() {
        return value;
    }

    public void setValue(int newValue) {
        value = newValue;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof A) {
            return this.value == ((A) o).value;
        }
        return super.equals(o);
    }

    @Override
    public int hashCode() {
        return Objects.hash(value);
    }
}

通过重写这个方法,你可以定义两个对象如何被视为相同。你也应该定义 hashCode() 方法。

英文:

Redefine Class A like this:

Class A
{
    int value;
    public A(int newValue)
    {
        setValue(newValue);
    }
    public int getValue()
    {
         return value;
    }
    public void setValue(int newValue)
    {
         value = newValue;
    }
    public boolean equals(Object o)
    {
         if( o instanceof A)
         {
             return this.value == ((A)o).value;
         }
         return super.equals(o);
    }
}

By overriding this method, which uses the object's memory address by default, you are defining how two object should be considered the same.

You should also define the hashcode() method.

答案2

得分: 1

以下是翻译好的内容:

在Java中,每个类在某个时候都会继承Object类。Object类有一个方法equals(),每个类都会继承它。你应该重写它来检查传递的对象是否与当前对象相等。

这将解决你在List方面的问题。让我们来看看ArrayList.remove()的JavaDoc - 它说:
> 删除具有最低索引i的元素,使得(o==null ? get(i)==null : o.equals(get(i)))(如果存在这样的元素)。

ArrayList会遍历列表中的每个条目,并调用其equals()方法将其与传递的对象进行比较。
因此,你可以通过重写equals方法来添加你的A类,并让它检查某种属性,以确保它是相同的对象。你还可以实现其他方法来确保对象相等,比如生成哈希码并进行比较,或者比较实际的对象ID。

以下是在你的A类上实现此类方式的示例:

class A
{
    int value;
    public A(int newValue)
    {
        setValue(newValue);
    }
    public int getValue()
    {
         return value;
    }
    public void setValue(int newValue)
    {
         value = newValue;
    }
    @Override
    public boolean equals(Object obj) 
    {
        if(obj != null && obj instanceof A)
        {
            A tmp = (A)obj;
            if(tmp.getValue() == this.value) return true;
            else return false;
        }
        
        return false;
    }
}
英文:

In Java every Class is extending Object at some point. Object got a method equals() which every class inherits. You should overwrite it to check if the passed object is equal to the current one.

It would solve your problem with the List. Lets take a look at the ArrayList.remove() JavaDoc - It says:
> removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists).

ArrayList goes through every entry in the List and calls the equals() method of it to compare it to the passed Object.
So you could append your Class A by overriding the equals method and let it check on some kind of attribute to make sure it's the same Object. You could also implement some other way to make sure the Objects are equal, like generating a hashcode and compare those or the actual object ID.

An example on how you could implement such a way on your Class A:

Class A
{
    int value;
    public A(int newValue)
    {
        setValue(newValue);
    }
    public int getValue()
    {
         return value;
    }
    public void setValue(int newValue)
    {
         value = newValue;
    }
    @Override
    public boolean equals(Object obj) 
    {
        if(obj != null &amp;&amp; obj instanceof A)
        {
            A tmp = (A)obj;
            if(tmp.getValue() == this.value) return true;
            else return false;
        }
        
        return false;
    }
}

答案3

得分: 0

尽管您正在使用相同的值初始化 A 的新对象,但这些对象是不同的,具有不同的内存,因此您只需移除具有该内存位置的现有对象。

我建议您遍历数组,通过过滤找到值为 5 的元素,然后将该元素从数组中移除。

您可以使用 filter 方法来移除添加的对象。
您的代码看起来可能像这样:

valuesOfA = valuesOfA.stream().filter(obj -> !obj.getValue().equals(5));

现在,您的 valuesOfA 数组不再具有先前添加的值为 5 的对象。

英文:

Though you are initializing the new object of A with same value, the objects are different having different memories, so you just have to remove the existing object having that memory location only.

I would suggest you to traverse the array and find the value 5 by filtering it and then removing that element from the array.

You could just use filter method for removing the added object.
Your code would look something like this:

valuesOfA = valuesOfA.stream().filter(obj -&gt; !obj.getValue().equals(5));

Now your valuesOfA array is not having the object whose value was 5 that you added before

huangapple
  • 本文由 发表于 2020年5月30日 16:07:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/62099574.html
匿名

发表评论

匿名网友

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

确定