简体   繁体   中英

trying to remove a specific object from arraylist

    class EX6
    {
        private int value;

        public static void main(String [] args)
        {
            Scanner input = new Scanner(System.in);
            System.out.println("Enter some numbers (all on one line, separated by spaces):");
            String line = input.nextLine();
            String[] numbers = line.split(" +");
            ArrayList<Integer> a = new ArrayList<Integer>();

            for(int i=0; i<numbers.length; i++)
                a.add(new Integer(numbers[i]));
            System.out.println("The numbers are stored in an ArrayList");
            System.out.println("The ArrayList is "+a);

            EX6 ex = new EX6();
            ex.value = Integer.parseInt(JOptionPane.showInputDialog("Enter a number"));

            System.out.println(removeNumber(a,ex));
        }

        public static <T> ArrayList<T> removeNumber(ArrayList<T> a, EX6 e)
        // Adds n after every occurrence of m in a, constructively.
        {
            ArrayList<T> b = new ArrayList<T>();
            for(int i=0; i<a.size(); i++)
            {
                if(a.get(i) == e)
                {
                    a.remove(i);
                }
            }
            return a;

If I enter the values [5,12 ,4, 16,4] into the ArrayList , and I type 4 into the JOptionPane , I would like to remove all the 4 's from the list.

HOW WOULD I PASS ex.value to the method removeNumber()???

您可以重复使用ArrayList.remove(Object)

ArrayList al = ...; int elementToRemove = ...; boolean found; do { found = al.remove((Integer)elementToRemove); } while (found);

You can try this, just define the Iterator and iterator through it, find the matched element which you want to delete and than delete form the iterator. It will delete the element form the Arraylist as Iterator is referring to Arraylist.

public static <T> ArrayList<T> removeNumber(ArrayList<T> a, EX6 e)
{
       Iterator i = a.iterator();
       while(i.hasNext())
       {
           if(i.next().equals((Integer)e.value))
           {
            i.remove();
           }
       }
       return a;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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