简体   繁体   English

如何从 Java 中的 ArrayList 中删除特定对象?

[英]How to remove specific object from ArrayList in Java?

How can I remove specific object from ArrayList?如何从 ArrayList 中删除特定对象? Suppose I have a class as below:假设我有一个类如下:

import java.util.ArrayList;    
public class ArrayTest {
    int i;

    public static void main(String args[]){
        ArrayList<ArrayTest> test=new ArrayList<ArrayTest>();
        ArrayTest obj;
        obj=new ArrayTest(1);
        test.add(obj);
        obj=new ArrayTest(2);
        test.add(obj);
        obj=new ArrayTest(3);
        test.add(obj);
    }
    public ArrayTest(int i){
        this.i=i;
    }
}

How can I remove object with new ArrayTest(1) from my ArrayList<ArrayList>如何从我的ArrayList<ArrayList>删除带有new ArrayTest(1)对象

ArrayList removes objects based on the equals(Object obj) method. ArrayList基于equals(Object obj)方法删除对象。 So you should implement properly this method.所以你应该正确地实现这个方法。 Something like:就像是:

public boolean equals(Object obj) {
    if (obj == null) return false;
    if (obj == this) return true;
    if (!(obj instanceof ArrayTest)) return false;
    ArrayTest o = (ArrayTest) obj;
    return o.i == this.i;
}

Or要么

public boolean equals(Object obj) {
    if (obj instanceof ArrayTest) {
        ArrayTest o = (ArrayTest) obj;
        return o.i == this.i;
    }
    return false;
}

If you are using Java 8:如果您使用的是 Java 8:

test.removeIf(t -> t.i == 1);

Java 8 has a removeIf method in the collection interface. Java 8 在集合接口中有一个removeIf方法。 For the ArrayList, it has an advanced implementation (order of n).对于 ArrayList,它具有高级实现(n 阶)。

In general an object can be removed in two ways from an ArrayList (or generally any List ), by index ( remove(int) ) and by object ( remove(Object) ).通常,可以通过两种方式从ArrayList (或通常任何List )中remove(int)对象,通过索引( remove(int) )和通过对象( remove(Object) )。

In this particular scenario: Add an equals(Object) method to your ArrayTest class.在此特定场景中:将equals(Object)方法添加到ArrayTest类。 That will allow ArrayList.remove(Object) to identify the correct object.这将允许ArrayList.remove(Object)识别正确的对象。

For removing the particular object from arrayList there are two ways.要从 arrayList 中删除特定对象,有两种方法。 Call the function of arrayList.调用arrayList的函数。

  1. Removing on the basis of the object.根据对象删除。
arrayList.remove(object);

This will remove your object but in most cases when arrayList contains the items of UserDefined DataTypes, this method does not give you the correct result.这将删除您的对象,但在大多数情况下,当 arrayList 包含 UserDefined DataTypes 的项目时,此方法不会为您提供正确的结果。 It works fine only for Primitive DataTypes.它仅适用于原始数据类型。 Because user want to remove the item on the basis of object field value and that can not be compared by remove function automatically.因为用户想根据对象字段值删除项目,而删除功能无法自动比较。

  1. Removing on the basis of specified index position of arrayList.根据arrayList 的指定索引位置进行删除。 The best way to remove any item or object from arrayList.从 arrayList 中删除任何项目或对象的最佳方法。 First, find the index of the item which you want to remove.首先,找到要删除的项目的索引。 Then call this arrayList method, this method removes the item on index basis.然后调用这个arrayList 方法,这个方法在索引的基础上删除项目。 And it will give the correct result.它会给出正确的结果。
arrayList.remove(index);  

Here is full example.这是完整的例子。 we have to use Iterator's remove() method我们必须使用迭代器的 remove()方法

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayTest {
    int i;
    public static void main(String args[]) {
        ArrayList<ArrayTest> test = new ArrayList<ArrayTest>();
        ArrayTest obj;
        obj = new ArrayTest(1);
        test.add(obj);
        obj = new ArrayTest(2);
        test.add(obj);
        obj = new ArrayTest(3);
        test.add(obj);
        System.out.println("Before removing size is " + test.size() + " And Element are : " + test);
        Iterator<ArrayTest> itr = test.iterator();
        while (itr.hasNext()) {
            ArrayTest number = itr.next();
            if (number.i == 1) {
                itr.remove();
            }
        }
        System.out.println("After removing size is " + test.size() + " And Element are :" + test);
    }
    public ArrayTest(int i) {
        this.i = i;
    }
    @Override
    public String toString() {
        return "ArrayTest [i=" + i + "]";
    }

}

工作演示屏幕

use this code使用此代码

test.remove(test.indexOf(obj));

test is your ArrayList and obj is the Object, first you find the index of obj in ArrayList and then you remove it from the ArrayList.
List<Object> list = new ArrayList();
for (Iterator<Object> iterator = list.iterator(); iterator.hasNext();) {
  Object obj= iterator.next();
    if (obj.getId().equals("1")) {
       // Remove the current element from the iterator and the list.
       iterator.remove();
    }
}

If you want to remove multiple objects that are matching to the property try this.如果要删除与该属性匹配的多个对象,请尝试此操作。

I have used following code to remove element from object array it helped me.我使用以下代码从它帮助我的对象数组中删除元素。

In general an object can be removed in two ways from an ArrayList (or generally any List), by index (remove(int)) and by object (remove(Object)).通常,可以通过两种方式从ArrayList (或通常任何 List)中删除object ,通过index (remove(int)) 和通过object (remove(Object))。

some time for you arrayList.remove(index) or arrayList.remove(obj.get(index)) using these lines may not work try to use following code.一些时间使用这些行arrayList.remove(index)arrayList.remove(obj.get(index))可能不起作用尝试使用以下代码。

for (Iterator<DetailInbox> iter = detailInboxArray.iterator(); iter.hasNext(); ) {
    DetailInbox element = iter.next();
   if (element.isSelected()) {
      iter.remove();
   }
}

I have tried this and it works for me:我试过这个,它对我有用:

ArrayList<cartItem> cartItems= new ArrayList<>();

//filling the cartItems

cartItem ci=new cartItem(itemcode,itemQuantity);//the one I want to remove

Iterator<cartItem> itr =cartItems.iterator();
while (itr.hasNext()){
   cartItem ci_itr=itr.next();
   if (ci_itr.getClass() == ci.getClass()){
      itr.remove();
      return;
    }
}

AValchev is right.阿瓦尔切夫是对的。 A quicker solution would be to parse all elements and compare by an unique property.更快的解决方案是解析所有元素并按唯一属性进行比较。

String property = "property to delete";

for(int j = 0; j < i.size(); j++)
{
    Student obj = i.get(j);

    if(obj.getProperty().equals(property)){
       //found, delete.
        i.remove(j);
        break;
    }

}

THis is a quick solution.这是一个快速的解决方案。 You'd better implement object comparison for larger projects.对于较大的项目,您最好实现对象比较。

This helped me:这帮助了我:

        card temperaryCardFour = theDeck.get(theDeck.size() - 1);
        theDeck.remove(temperaryCardFour);    

instead of代替

theDeck.remove(numberNeededRemoved);

I got a removal conformation on the first snippet of code and an un removal conformation on the second.我在第一个代码片段上得到了一个删除构象,在第二个代码片段上得到了一个未删除构象。

Try switching your code with the first snippet I think that is your problem.尝试使用第一个片段切换您的代码,我认为这是您的问题。

Nathan Nelson内森·纳尔逊

simple use remove() function.简单使用 remove() 函数。 and pass object as param u want to remove.并将对象作为您要删除的参数传递。 ur arraylist.remove(obj)你的arraylist.remove(obj)

or you can use java 8 lambda或者你可以使用 java 8 lambda

test.removeIf(i -> i==2); test.removeIf(i -> i==2);

it will simply remove all object that meet the condition它将简单地删除所有满足条件的对象

Below one is used when removed ArrayTest(1) from test ArrayList当从测试 ArrayList 中删除 ArrayTest(1) 时使用下面的一个

test.removeIf(
     (intValue) -> {
         boolean remove = false;
         remove = (intValue == 1);
         if (remove) {
            //Success
         }
         return remove;
      });
 private List<Employee> list = new ArrayList<>();
 list.removeIf(emp -> emp.getId() == 10);
    ArrayTest obj=new ArrayTest(1);
    test.add(obj);
    ArrayTest obj1=new ArrayTest(2);
    test.add(obj1);
    ArrayTest obj2=new ArrayTest(3);
    test.add(obj2);

    test.remove(object of ArrayTest);

you can specify how you control each object.您可以指定如何控制每个对象。

You can use Collections.binarySearch to find the element, then call remove on the returned index.您可以使用 Collections.binarySearch 来查找元素,然后在返回的索引上调用 remove。

See the documentation for Collections.binarySearch here: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#binarySearch%28java.util.List,%20java.lang.Object%29请参阅此处的 Collections.binarySearch 文档: http : //docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#binarySearch%28java.util.List,%20java.lang。对象%29

This would require the ArrayTest object to have .equals implemented though.这将需要 ArrayTest 对象实现 .equals 。 You would also need to call Collections.sort to sort the list.您还需要调用 Collections.sort 来对列表进行排序。 Finally, ArrayTest would have to implement the Comparable interface, so that binarySearch would run correctly.最后,ArrayTest 必须实现 Comparable 接口,这样 binarySearch 才能正确运行。

This is the "proper" way to do it in Java.这是在 Java 中执行此操作的“正确”方法。 If you are just looking to solve the problem in a quick and dirty fashion, then you can just iterate over the elements and remove the one with the attribute you are looking for.如果您只是想以一种快速而肮脏的方式解决问题,那么您可以遍历元素并删除具有您正在寻找的属性的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM