remove duplicates from object array data java
i want to know how to remove duplicates in object.
for example
cat c[] = new cat[10];
c[1].data = "ji";
c[2].data =开发者_如何学Python "pi";
c[3].data = "ji";
c[4].data = "lp";
c[5].data = "ji";
c[6].data = "pi";
c[7].data = "jis";
c[8].data = "lp";
c[9].data = "js";
c[10].data = "psi";
i would like to remove the duplicates value from object array.
thanks and advance
I assume you want to create another array which is duplicate free. (as you cannot change the size of an array)
You could implement hashCode and equals and use a HashSet, however without these you can create a Comparator.
However the simplest approach may be using the "Cat" class and "cats" array
Cat[] cats = { ... };
Set<String> datas = new HashSet<String>();
List<Cat> catList = new ArrayList<Cat>();
for(Cat cat: cats) if(datas.add(cat.data)) catList.add(cat);
Cat[] unqiueCats = catList.toArray(new Cat[catList.size()]);
Something like this should work? Make sure to import java.util.Arrays and java.util.HashSet.
/**
* Removes duplicates from an array. Objects in the array must properly
* implement hashCode() and equals() for this to work correctly.
*/
public static <E> E[] removeDuplicates(E[] array) {
// convert input array to populated list
List<E> list=Arrays.asList(array);
// convert list to populated set
HashSet<E> set=new HashSet<E>();
set.addAll(list);
// convert set to array & return,
// use cast because you can't create generic arrays
return (E[]) set.toArray();
}
You can create another temporary array, loop through the original array, and for each element, check if the value already in the temp array or not. If not, add it in.
You can also use Set and override the equals and hashCode method
Here's a quick hack to do what you wanted to (hopefully also compiles):
// Assuming the code in the question is here.
java.util.List<cat> tmp = new java.util.LinkedList<cat>();
java.util.HashSet<String> set = new HashSet<String>();
for (int i = 0; i < c.length; ++i)
if (set.put(c[i].data)) tmp.add(c[i]);
c = tmp.toArray(c);
精彩评论