-1

I have got class TestObject with two variables: int A, and int B. I have got a list of TestObjects, and I would like to remove from the list duplicates (Objects that contains the same A and the same B variable.)

  • Object 1 (A=1,B=1)
  • Object 2 (A=2,B=2)
  • Object 3 (A=1,B=1)

In this case I would like to remove from the list Object 1 OR 3, it doesn't matter which.

Objects are different instances, so standard:

LinkedHashSet<TestObject> hs = new LinkedHashSet<TestObject>();
    hs.addAll(TestObjectList);
    new.clear();
    new.addAll(hs);

This will not work. Is there any easy way to achieve my goal? I tried using iterator inside iterator:

        ListIterator<TestObject> iter =  TestObjectList.listIterator();
        while(iter.hasNext()){
            TestObject to = iter.next();
            ListIterator<TestObject> iter2 =  TestObjectList.listIterator();
            while(iter2.hasNext()){
                TestObject to2 = iter2.next();
                if(to.A==to2.A && to.B == to2.B){
                    iter.remove();
                }
            }
        }

But I get following exception:

Exception in thread "main" java.util.ConcurrentModificationException' on line "TestObject to2 = iter2.next();

Unfortunnately, I have no other idea in what way I may achieve this goal. Maybe there is an easier way?

user2004685
  • 9,548
  • 5
  • 37
  • 54
Thamiar
  • 600
  • 7
  • 22

2 Answers2

3

As @DeludedPsyche has said, you just need to make TestObject support proper Java equality checking. Then you can add instances to a Set and have duplicates 'ignored'.

There are lots of good links for learning more about how / why this works, e.g. here and here.

Eclipse generated this for me:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + a;
    result = prime * result + b;
    return result;
}

@Override
public boolean equals( Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (!(obj instanceof TestObject)) {
        return false;
    }
    TestObject other = (TestObject) obj;
    if (a != other.a) {
        return false;
    }
    if (b != other.b) {
        return false;
    }
    return true;
}
Community
  • 1
  • 1
Andrew Regan
  • 5,087
  • 6
  • 37
  • 73
  • That is exactly what solves my problem. What is more, thank you very much for links! They helped me to understand this issue. – Thamiar Feb 11 '16 at 07:55
1
  1. Override equals and hashcode in TestObject class using your members i.e. A and B.
  2. Put all TestObject Objects into a Set implementation.
DeludedPsyche
  • 131
  • 1
  • 2
  • 13