0
    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()???

jayd
  • 11
  • 6
  • 4
    what is wrong with a.removeAll(Collection.singletonList(e)) Also you split should be line.split("\\s+"); – StackFlowed Oct 07 '14 at 18:41
  • Proper way is to use an Iterator instead [See this Answer](http://stackoverflow.com/questions/9691328/removing-object-from-arraylist-in-for-each-loop) – gtgaxiola Oct 07 '14 at 18:41
  • if i type that in, nothing happens, still get [5,12,4,16,4] – jayd Oct 07 '14 at 18:43
  • never used Iterators before, is there another way of doing it – jayd Oct 07 '14 at 18:45
  • Slightly alternative option which is slower (granted) but you could loop through the original list and copy the elements to a new list, but only if they don't equal the value you don't want in the new list. – Dan Temple Oct 07 '14 at 18:47

2 Answers2

0

You can use ArrayList.remove(Object) repeatedly

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

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
0

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;
}
Moni
  • 433
  • 3
  • 9