Loading...
Logo
Processing Forum
I know this topic is more related to java than processing but i think it might be useful to this community.

How to remove duplicates from an array in a correct manner ?

I've googled a bit and found some interesting threads on stackoverflow but i finally became confuse.
What i mean by correct manner, is just the less memory consuming and fast computation.
Does that need a function that would convert(by checking and adding values) an Array into a Set ?
I'm sure some java gurus have already did that many times.

Regards.

Replies(3)

" less memory consuming and fast computation"
Algorithms often have to make compromises between the two, you rarely get both...
Memory being quite cheap today, and fast computation being important in real-time programs like most sketches are, we often sacrifice memory to get faster algorithm.
One issue is to remember the values we have already seen. Either we compare each value to all the previous ones, and discard it if it is already in the array (slow), or we find a structure that automatically overwrites existing values. That's the Set.
Such structure costs very little when we deal with an array of objects (including strings) but is more costly with arrays of primitive values (integers or floats) as we have to box and unbox the values in objects.
Here is a simple examples with strings:
Copy code
  1. String[] values =
  2. {
  3.   "Audi",
  4.   "Renault",
  5.   "Mercedes",
  6.   "BMW",
  7.   "Peugeot",
  8.   "Renault",
  9.   "VW",
  10.   "Audi",
  11.   "BMW"
  12. };
  13.  
  14. void setup()
  15. {
  16.   Set<String> set = new HashSet<String>();
  17.   Collections.addAll(set, values);
  18.   String[] uniques = set.toArray(new String[0]);
  19.   println(uniques);
  20. }

Ok many many thanks for your answer, it was simpler than i thought.

I had this question related to that topic.
I'll see if i can get it to works with RPoint Objects.
Ah, for custom objects, to make it work, you have to have them implementing proper hashCode() and equals() methods.
It doesn't seem to be the case for RPoint.