• Post Reply Bookmark Topic Watch Topic
  • New Topic

Efficient??? Can you do better?  RSS feed

 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the deal:

I have a vector with some objects inside and I don't want to have duplications.

What I did is create a SET that has only the KEYS (let's say the an object has a key and another field, but the key is what makes it uniwe)

I loop through the vector and find if the key exist more than once.


QUESTION: Is there a better way to do that?

this is my code

Set s = new HashSet();


//make a set with uniqe KEYS
for (int x=0; x<model.size(); x++)
{
Record tmp = (Record) model.elementAt(x);
s.add(tmp.getKEY());
}

Iterator sItr = s.iterator();



while (sItr.hasNext())
{
String sValue = sItr.next().toString();
boolean flag=false;

//loop thru the vector and find dupplications
for (int i=0; i<model.size(); i++)
{

Record tmp = (Record) model.elementAt(i);

if(sValue.equals(tmp.getKEY()))
{
if (flag)
{
//remove item
model.removeElementAt(i);
}
else
{
//fount it for the first time.
flag=true;
}
}
}
}
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you bumped into Map yet? Map is an interface with a number of implementations. The idea is to store and retrieve objects by keys. Look for Map and the implementing classes in the JavaDoc. HERE is a crib sheet I use to choose the right collection some times. It's likely that HashMap will meet your needs.
 
David Hibbs
Ranch Hand
Posts: 374
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're already using HashSet; why go to such trouble? If the objects you put into the set have a single property that makes them unique, use it as the hash code. Simply override both equals() and hashCode(), then insert your objects into your HashSet.

@see java.util.HashSet api
@see java.lang.Object api

Oh, and @see Josh Bloch's Effective Java on how to correctly implement equals and hashCode.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!