This is my current attempt to remove duplicates from an array holding integers, but this does not give me any results. It simply prints out nothing. Any help would be greatly appreciated.
public static void duplicate(int numbers[], int size)
{
for (int i = 0; i < size; i++){
boolean duplicate = false;
int b = 0;
while (b < i){
if (numbers[i] == numbers[b])
duplicate = true;
b++;}
if (duplicate = false)
System.out.print(numbers[i] + " ");}
}
asked Nov 18, 2014 at 15:41
-
this should work fine. just change = with == in the last if.İsmet Alkan– İsmet Alkan2014年11月18日 15:44:10 +00:00Commented Nov 18, 2014 at 15:44
3 Answers 3
Try this:
public static void duplicate(int numbers[], int size)
{
for (int i = 0; i < size; i++){
boolean duplicate = false;
int b = 0;
while (b < i){
if (numbers[i] == numbers[b])
duplicate = true;
b++;}
if (duplicate == false)
System.out.print(numbers[i] + " ");}
}
You need to use ==
not =
in your if statement.
answered Nov 18, 2014 at 15:42
You can also make use of HashSet or LinkedHashSet to Preserve the ordering
public void removeDupInIntArray(int[] ints){
Set<Integer> setString = new LinkedHashSet<Integer>();
for(int i=0;i<ints.length;i++){
setString.add(ints[i]);
}
System.out.println(setString);
}
answered Nov 18, 2014 at 15:47
The best choice would be to use the Sets(Hash Linkedhash) so duplicates can be avoided
answered Nov 18, 2014 at 19:40
lang-java