Remove duplication from array – Java

A question was posted on the forum where a user had an array and wanted to remove the duplication. The user was attempting to use the System.arraycopy() method for some reason, which was a shame because most of the code they had written appeared to be in place.

Answer:

Two fold really. Firstly I started with creating a new array to copy elements into, but then realised afterwards that I couldn’t declare the size of the new array as I didn’t know how many duplicate items were going to be removed. (I also experienced a crash in my browser whilst writing this blog post and have now subsequently lost that code! – if anyone if desperate for it, it’ll take a few minutes to post back up). However, rather than declaring a new array, a simple ArrayList would have sufficed, until…

Having read the answers to the original question, someone recommended using Sets, so I did a little reading around these. This produced a much nicer solution:

char[] myArray = new char[6];
myArray[0] = 'g';
myArray[1] = 'j';
myArray[2] = 'a';
myArray[3] = 'g';
myArray[4] = 'x';
myArray[5] = 'y';

Set resultSet = new HashSet();

for (int i = 0; i < myArray.length; i++) {
   if (!resultSet.add(myArray[i]))
       System.out.println("Duplicated detected: " + myArray[i]);
}

System.out.println(resultSet);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s