dcsimg
Adding elements to any Collection without repeats?
3 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Shahmil_Merchant
Posted On:   Thursday, August 22, 2002 09:58 AM


I am retrieving values from a file and storing them into an ArrayList.But each time I want to ensure that i dont add repeats.The way i am think of doing this is to run through the ArrayList each time and check for equality and if the value does not exist then i add to the ArrayList.I am not too sure if this is the best implementation.

Re: Adding elements to any Collection without repeats?

Posted By:   Steven_Martin  
Posted On:   Thursday, August 22, 2002 12:02 PM

Use a Set, implemented as TreeSet.

Re: Adding elements to any Collection without repeats?

Posted By:   Steven_Martin  
Posted On:   Thursday, August 22, 2002 12:02 PM

Use a Set, implemented as TreeSet.

Re: Adding elements to any Collection without repeats?

Posted By:   Lasse_Koskela  
Posted On:   Thursday, August 22, 2002 10:49 AM

You could improve performance by using a HashMap for figuring out whether the value doesn't exist already in the ArrayList. Of course, if you don't need the values to be kept in order, you could use a Set, which guarantees all values to exist only once by definition.


I would probably write a class (e.g. my.package.ValueList), which would have an ArrayList and a HashMap as instance variables.


Some sketchy code:


public class ValueList
{
/**
* Stores the added values maintaining order.
*/
private List valueList;

/**
* Stores the added values for faster search.
*/
private HashMap valueMap;

/**
* Trivial constructor, which initializes the underlying
* data structures.
*/
public ValueList()
{
this.valueList = new ArrayList();
this.valueMap = new HashMap();
}

/**
* Adds the given object to the list, if the value
* doesn't exist yet.
*/
public void add(Object obj)
{
if (this.valueMap.containsKey(obj) == false)
{
this.valueList.add(obj);
this.valueMap.put(obj, "obj exist");
}
}

}
About | Sitemap | Contact