tags:

views:

772

answers:

3

Hi i have a ArrayList

 ArrayList<String> values=new ArrayList<String>();
 values.add("s");
 values.add("n");
 values.add("a");
 values.add("s");

In this i want to remove repeated value

Please Help me

Thanks in Advance

A: 

I think a real neat solution for enforcing unique array lists is this one, if it's not too much code for what you're trying to achieve.

David Hedlund
Thank you so much
Kumar
Common practice is to ACCEPT the answer, if you like it...
Johan Wikström
+3  A: 

Why dont you use a set then ?

Cshah
A: 

The class David Hedlund suggested can be made a lot shorter:

public class UniqueArrayList extends ArrayList {
    /**
     * Only add the object if there is not
     * another copy of it in the list
     */
    public boolean add(T obj) {
        if(this.contains(obj))
           return false;
        return super.add(obj);
    }

    public boolean addAll(Collection c) {
        boolean result = false;
        for (T t : c) {
            if (add(t)) {
                result = true;
            }
        }
        return result;
    }
}

The addAll operation is modified too. The documentation states:

Returns: true if this list changed as a result of the call.

I modified the method to reflect this behaviour. There's still one problem. The documentation of the addAll() method also states:

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.

The order might be broken by using this method. A possible workaround for this problem might be not supporting the addAll method.

Scharrels
This makes adding an element O(n). Use a Set instead!
Kevin Bourrillion