user1156596
user1156596

Reputation: 601

Preventing duplicate items in list from printing to cell table gwt

If I have a class called 'TestClass' full of getters and setters, and then I set some properties on the class object in another class like so:

            TestClass testClass = new TestClass();

            testClass.setAppId("id");
            testClass.setStatus("Status");
            testClass.setMessage("Message");

            List<TestClass> list = dataProvider.getList();

And then, before adding this object to my java list, I have to make sure it doesn't exist in the list to avoid duplicates.

To achieve this, I do the following check to see if all three properties of the corresponding values exist in the testClass object present in the list. If they don't, then it may be added to the list.

            if(!list.contains(testClass.getAppId().equals("id")) &&
               !list.contains(testClass.getStatus().equals("Status")) &&
               !list.contains(testClass.getMessage().equals("Message"))) {
                list.add(testClass);
            }

     dataProvider.refresh();

The above code is within a click handler, so is only ever executed when a button is clicked.

Why then, despite my futile attempt at stopping duplicates from entering the list, do I fail to stop duplicate records being added to my cell table in gwt?

Am I wrong in thinking the list logic is the problem?

Thank you for your help, I hope I've been thorough enough.

Upvotes: 0

Views: 190

Answers (2)

enrybo
enrybo

Reputation: 1785

Your testClass.getAppId().equals("id") call returns true or false. Your list does not "contain" true or false therefore the condition becomes true and the element is added. The code should look like this:

for(TestClass testClass: list){

    if(!testClass.getAppId().equals("id") &&
        !testClass.getStatus().equals("Status") &&
        !testClass.getMessage().equals("Message")){

        list.add(testClass);
    }
}

dataProvider.refresh();

Upvotes: 1

istovatis
istovatis

Reputation: 1408

testClass.getAppId().equals("id") returns true or false, weather your id equals to "id" or not. You then check if your list contains the return of this call. That's why you fail to maintain only unique items in your list.

You can create an equals/compare method in your testClass class so as to define in this function if the item that is going to be inserted already exists in your structure.

As a general approach is also better to use a hash in order to be sure that your data structure always stores unique items.

Upvotes: 1

Related Questions