user2816215
user2816215

Reputation: 431

Error in my code: Find unique elements of an arraylist

I was trying to write the code to find the unique elements of an ArrayList via two loops. items is the list contains elements and duplicates and uniqueitems contains one copy of each. eg:

Here is the code:

uniqueitems.add(items.get(0));
for(int i=0;i<items.size();i++)
{
    count=0;
    for(int j=0;j<uniqueitems.size();j++)
    {
        if(items.get(i).equals(uniqueitems.get(j)))
        {
            count++;
            break;
        }
    }
    if(count==0)
    {
        n++;
        uniqueitems.add(items.get(n));

    }
}

I'm trying to figure out my mistake.

Upvotes: 1

Views: 108

Answers (3)

deme72
deme72

Reputation: 1153

A simpler solution:

uniqueitems.add(items.get(0));
for(int i=1;i<items.size();i++){
    if(!uniqueitems.contains(items.get(i))){
        uniqueitems.add(items.get(i));
    }
}

list.contains(Object o) returns true if o is in list

Google is a programmer's friend, try not to re-write methods that already exist.

Upvotes: 1

wltrup
wltrup

Reputation: 798

Rather than write your own code, there's a much simpler and more robust solution: use a set data structure. A set, by definition, can only contain unique elements, i.e., no duplicates.

Java has several implementations of the Set interface. I'd suggest using java.util.HashSet. Essentially, you instantiate a HashSet from your ArrayList (which automatically discards duplicates) then extract another ArrayList from the set you just created. That array will contain only the unique elements of your original array.

Upvotes: 1

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Here:

uniqueitems.add(items.get(n));

If items.get(i) hasn't been found, then you should add that element in the uniqueitems:

uniqueitems.add(items.get(i));

Don't use that n variable.

Also, check if your equals method works as expected.

And, if this isn't a homework and your class already overrides equals and hashCode methods, then you may use this one-line approach:

List<YourClass> uniqueItems = new ArrayList<>(new LinkedHashSet<>(items));

Upvotes: 2

Related Questions