Ghassen Bellagha Ghassen Bellagha - 3 days ago 6
Java Question

delete duplicates in Vector of data structure

I have a

Vector
, each cell is containing a
Data Structure
:

public class objet_poid_n {
public int Num;
public double Poid;
}


The problem is that the Vector may have duplications and i need to create a function or procedure able to delete duplicates ..
I tried this one and it couldn't help ..

public static void removeDuplicates(Vector v)
{
for(int i=0;i<v.size();i++){
for(int j=0;j<v.size();j++)
{
if(i!=j)
{
if(v.elementAt(i).equals(v.elementAt(j)))
{
v.removeElementAt(j);
}
}
}
}
}


Any Ideas ?

Answer

First you should implement an equals() method in your objet_poid_n because the default behavior compares memory addresses.

Then you could either use the method Vector.contains() before inserting a new object in your vector or use a Set which is by definition a collection without duplicates.

Comments