ubuntuguy
asked on
Removing duplicates from an array
Hi guys,
I have a file from which I'm reading a Point objects. I put them into an array, and I need to remove any duplicates. I think my code should work, but when I check the elements in the array, duplicates are still there. Can you please provide some feedback on what I'm doing wrong?
p.s. The code to initially fill the array works, the only problem that I have is that the duplicates are not being removed. (Lines 8 to 10)
I have a file from which I'm reading a Point objects. I put them into an array, and I need to remove any duplicates. I think my code should work, but when I check the elements in the array, duplicates are still there. Can you please provide some feedback on what I'm doing wrong?
p.s. The code to initially fill the array works, the only problem that I have is that the duplicates are not being removed. (Lines 8 to 10)
public void fillArray(){
array = new Point[this.arraySize()];
String line = fileReader.readLine();
for(int i=0; line!=null; i++){
array[i] = this.convertPoint(line);
line = fileReader.readLine();
}
List<Point> list = Arrays.asList(array);
Set<Point> set = new HashSet<Point>(list);
array = (Point[])set.toArray(new Point[]{});
}
The Point must be able to be compared if I am not mistaken as the Set/HashSet will not allow duplicates, but it must have some way to tell if one Point object is equal to another Point object in order to work.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks guys, chaituu solution worked very well for strings, then I simply put the array of string into a new array converting each string into a point.