elemein
elemein

Reputation: 207

Arraylist not removing object correctly?

I have some code.

     @Override
        public void handle(ActionEvent event) {

            System.out.println(counter.get(0));

            fileHolder.remove(counter.get(0));

            try {
                        FileWriter writer = new FileWriter("videoGameDatabase.txt");
                        for (int i=0;i<fileHolder.size();i++) {

                        writer.write(fileHolder.get(i));

                        if(i < fileHolder.size()-1) writer.write("\r\n");

                        }

                        writer.close();
                    } catch (IOException ex) {
                        Logger.getLogger(FinalProject.class.getName()).log(Level.SEVERE, null, ex);
                    }

        }
    });

Here, I am trying to delete an element in an array list. When I try to use this button to delete the entry, it does not work. Counter's first element's value is 1.

However, when I do:

           fileHolder.remove(1);

it works perfectly fine, yet both values are 1.

Why does the first one not work but the second one does?

Upvotes: 0

Views: 90

Answers (3)

Austin
Austin

Reputation: 8575

One word: Autoboxing. The Java Collections Framework automatically boxes primitive values with their corresponding object, e.g. int is auto-boxed as an Integer before it is stored in a Collection such as an ArrayList. This causes ambiguity when using a List<Integer> because there are two remove methods, namely remove(int) and remove(Object).

Solution: You should use an explicit cast to call the correct remove method when using an ArrayList<Integer>.

  • Use list.remove((Integer)x) when removing by value
  • Use list.remove((int)x) when removing by index

Note: Do not use list.remove(new Integer(x)). This unnecessarily creates a new Integer instance every time it is called. Instead, use the explicit cast (as shown above) or the Integer.valueOf method; these both take advantage of the autoboxing cache.

Upvotes: 1

blameitontheboogie
blameitontheboogie

Reputation: 49

I can't see how you read/store values from/in an array. Maybe there's a problem - reading always first value....

Upvotes: 0

KevinO
KevinO

Reputation: 4403

Please review the Javadocs for ArrayList. ArrayList has two remove methods, one of which takes an int, and removes at an index. The other takes an Object.

If you have stored integers in the ArrayList, and then attempt to remove by an int, you will remove by the index, not the object.

You need to carefully review the code for what is being returned. If counter.get(0) returns an int, you will then remove the object at the specified index.

Upvotes: 0

Related Questions