0

How can i remove duplicate elements from an unsorted array...?

I need the code to remove duplicates without sorting

8th Aug 2016, 2:16 PM
Ahmed Shafeeu
Ahmed Shafeeu - avatar
6 Respostas
+ 1
Couple of questions on this one. Remove or print out? If remove, remove and leave index null or resize array? Finally, possible to use list instead?
8th Aug 2016, 3:26 PM
James
James - avatar
+ 1
Wachirakorn had a great hashset example in a question right below yours. You should be able to use his example and alter it to fit your needs with very little effort.
8th Aug 2016, 4:11 PM
James
James - avatar
+ 1
import java.util.LinkedHashSet; import java.util.Set; public class Program { public static void main(String[] args) { int x[] = { 9,1,2,3,4,5,6,7,8,9,3,6,7 }; Set<Integer> set = new LinkedHashSet<Integer>(); for(int i : x){ if(!set.contains(i)){ set.add(i); } } x = new int[set.size()]; int index = 0; for(int i : set){ x[index++]=i; } for(int i : x){ System.out.print(i+" "); } } }
8th Aug 2016, 7:20 PM
WPimpong
WPimpong - avatar
0
We cannot remove an element from java basic array []. We need Set to remove duplicate elements. Then create a new array from the Set.
8th Aug 2016, 3:43 PM
WPimpong
WPimpong - avatar
0
I want to remove.. resized.. list can be used.. but finally it should return an array
8th Aug 2016, 4:06 PM
Ahmed Shafeeu
Ahmed Shafeeu - avatar
0
I just used it... but I don't know how to re size the array
8th Aug 2016, 6:17 PM
Ahmed Shafeeu
Ahmed Shafeeu - avatar