2

I have a system that involves loading 'PlayerValue' Objects. The objects are formatted as such: [Header] value. I have these saved in a text file and whenever I save or read from the file, I want to remove duplicate headers. So I did this:

first, I load all of the PlayerValues from the file into an ArrayList called 'array', then:

for (PlayerValue v : array) {
            for (PlayerValue v1 : array) {
                if (v1.header.equals(v.header)) {
                    array.remove(v1);
                }
            }
        }

Here you can see, it goes through each item of the array, then for each item, it searches the array again for the same header.

This would effectively remove duplicate headers, except for the fact that it throws a ConcurrentModificationException.

Any help for a work around?

3
  • Use a Set such as a HashSet rather than an ArrayList. Sets do not allow duplicates. Otherwise to remove from a collection while iterating, use an Iterator. Commented Oct 12, 2013 at 21:31
  • I could deal with duplicate entries, but two PlayerValues could have the same header with different values (thus making them unequal) and the ArrayList.contains method would ignore it. Commented Oct 12, 2013 at 21:34
  • @HovercraftFullOfEels The only issue is that he wants to remove duplicates based on some attribute, not just based on whether the objects are equal. Commented Oct 12, 2013 at 21:35

1 Answer 1

2

Even if this worked, it would be a bad way to remove duplicates. A better option would be to have a Map<Header, PlayerValue>:

Map<String, PlayerValue> map = new HashMap<>();

for (PlayerValue v : array)
    map.put(v.header, v);

Now you can iterate through this map's entries, which will not contain duplicate keys (headers):

array.clear();

for (Entry<?, PlayerValue> e : map.entrySet())
    array.add(e.getValue());
Sign up to request clarification or add additional context in comments.

6 Comments

Header isn't a separate object, it is an attribute of PlayerValue.
@LegendOfFailure What is it, a String?
Yes, it is. so you couldn't use 'Header' in the Object input of a Map<>
Thats what I was doing, I completely forgot about HashMap.
If I wanted to go further, I could edit the rest of the method to use only the map, instead of the ArrayList
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.