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

时间:2011-12-15 13:24:42

标签: java arraylist

如何从ArrayList中删除特定对象? 假设我有一个如下课程:

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;
    }
}

如何从new ArrayTest(1)

中删除ArrayList<ArrayList>的对象

17 个答案:

答案 0 :(得分:27)

ArrayList根据equals(Object obj)方法删除对象。所以你应该正确实现这个方法。类似的东西:

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;
}

答案 1 :(得分:10)

通常,可以通过索引(ArrayList)和对象(List)以两种方式从remove(int)(或通常为任何remove(Object))移除对象

在此特定方案中:向ArrayTest课程添加equals(Object)方法。这将允许ArrayList.remove(Object)识别正确的对象。

答案 2 :(得分:6)

如果您使用的是Java 8:

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

Java 8在集合界面中有一个removeIf方法。对于ArrayList,它具有高级实现(n的顺序)。

答案 3 :(得分:3)

从arrayList中删除特定对象有两种方法。调用arrayList的函数。

  1. 根据对象移除。
  2. arrayList.remove(object);
    

    这将删除您的对象,但在大多数情况下,当arrayList包含UserDefined DataTypes项时,此方法不会为您提供正确的结果。它仅适用于Primitive DataTypes。因为用户想要根据对象字段值删除项目,并且无法通过自动删除功能进行比较。

    1. 根据arrayList的指定索引位置进行删除。从arrayList中删除任何项目或对象的最佳方法。首先,找到要删除的项目的索引。然后调用此arrayList方法,此方法基于索引删除项目。它会给出正确的结果。
    2. arrayList.remove(index);  
      

答案 4 :(得分:1)

使用此代码

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.

答案 5 :(得分:1)

AValchev是对的。 更快的解决方案是解析所有元素并通过唯一属性进行比较。

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;
    }

}

这是一个快速的解决方案。您可以更好地为大型项目实施对象比较。

答案 6 :(得分:1)

这里是完整的示例。我们必须使用 迭代器的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 + "]";
    }

}

Working demo Screen

答案 7 :(得分:1)

 private List<Employee> list = new ArrayList<>();
 list.removeIf(emp -> emp.getId() == 10);

答案 8 :(得分:0)

您可以使用Collections.binarySearch查找元素,然后在返回的索引上调用remove。

请在此处查看Collections.binarySearch的文档: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#binarySearch%28java.util.List,%20java.lang.Object%29

这将要求ArrayTest对象实现.equals。您还需要调用Collections.sort来对列表进行排序。最后,ArrayTest必须实现Comparable接口,以便binarySearch能够正确运行。

这是在Java中执行此操作的“正确”方法。如果您只是想快速而肮脏地解决问题,那么您可以迭代元素并删除具有您正在寻找的属性的元素。

答案 9 :(得分:0)

这对我有所帮助:

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

而不是

theDeck.remove(numberNeededRemoved);

我在第一段代码上获得了删除构造,并在第二段中删除了构造。

尝试使用第一个代码段切换代码,我认为这是您的问题。

内森尼尔森

答案 10 :(得分:0)

    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);

您可以指定控制每个对象的方式。

答案 11 :(得分:0)

如果要删除与该属性匹配的多个对象,请尝试此操作。

我使用以下代码从它帮助我的对象数组中删除元素。

通常,可以通过ArrayList(或通常任何列表),index(删除(int))和object(删除(对象),以两种方式删除对象))。

使用这些行的某些时间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();
   }
}

答案 12 :(得分:0)

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();
    }
}

答案 13 :(得分:0)

我已经尝试过了,并且对我有用:

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;
    }
}

答案 14 :(得分:0)

简单使用remove()函数。并将对象作为要删除的参数传递。 ur arraylist.remove(obj)

答案 15 :(得分:0)

或者您可以使用Java 8 lambda

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

它只会删除所有符合条件的对象

答案 16 :(得分:0)

当从 test ArrayList

中移除 ArrayTest(1) 时使用下面的一个
    using System;
using System.IO;
using System.IO.Pipes;
using System.Threading;

class PipeClient
{
    static void Main(string[] args)
    {
        string path = @"D:\MyTest.txt";

        // This text is added only once to the file.
        if (!File.Exists(path))
        {
            // Create a file to write to.
            string createText = "test1" + Environment.NewLine;
            File.WriteAllText(path, createText);
        }

        using (NamedPipeClientStream pipeClient =
            new NamedPipeClientStream("TP"))
        {


            // Connect to the pipe or wait until the pipe is available..
            Console.Write("Attempting to connect to pipe...");
            pipeClient.Connect();

            string path2 = @"D:\MyTest2.txt";

            // This text is added only once to the file.
            if (!File.Exists(path2))
            {
                // Create a file to write to.
                string createText = "test2" + Environment.NewLine;
                File.WriteAllText(path2, createText);
            }

            Console.WriteLine("Connected to pipe.");
            Console.WriteLine("There are currently {0} pipe server instances open.",
               pipeClient.NumberOfServerInstances);
            /*using (StreamReader sr = new StreamReader(pipeClient))
            {
                // Display the read text to the console
                string temp;
                while ((temp = sr.ReadLine()) != null)
                {
                    Console.WriteLine("Received from server: {0}", temp);
                }
            }*/
            string path3 = @"D:\MyTest3.txt";

            // This text is added only once to the file.
            if (!File.Exists(path3))
            {
                // Create a file to write to.
                string createText = "test3" + Environment.NewLine;
                File.WriteAllText(path3, createText);
            }
                using (StreamWriter sw = new StreamWriter(pipeClient))
                {
                    sw.AutoFlush = true;
                    Console.Write("Enter text: ");
                    sw.WriteLine("123");
                }

                string path4 = @"D:\MyTest4.txt";

                // This text is added only once to the file.
                if (!File.Exists(path4))
                {
                    // Create a file to write to.
                    string createText = "test4" + Environment.NewLine;
                    File.WriteAllText(path4, createText);
                    Console.WriteLine("It reached this");
                }
                pipeClient.Dispose();

            }
        }
    }