views:

334

answers:

4

hi i want to know how to remove duplicates in object.

for example

cat c[] = new cat[10];

c[1].data = "ji";
c[2].data = "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

+1  A: 

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

vodkhang
Just use a `Set<Cat>` (specifically `HashSet<Cat>`), and implement `Comparable` or provide a `Comparator`.
Tom Hawtin - tackline
No, it should not implements Comparable. For Set and Map, you have to override the equals and hashCode method
vodkhang
+4  A: 

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()]);
Peter Lawrey
A: 

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);
megari
For some reason all the generics were stripped from my answer by the comment system. Oh well.
megari
@megari: for code snippet, indent 4 spaces in. The editor has a button for it, just highlight your code and click.
polygenelubricants
+1  A: 

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();
}
This is a nice, clever way to do this without any looping (in your code). The `addAll()` method, of course, will do all of that for you, and probably more efficiently since it can work with the internal implementation of the HashSet.
Craig Trader