user3808597
user3808597

Reputation: 47

Java remove duplicates from array using loops

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] + " ");}
    } 

Upvotes: 0

Views: 5669

Answers (3)

wwSlayerww
wwSlayerww

Reputation: 1

The best choice would be to use the Sets(Hash Linkedhash) so duplicates can be avoided

Upvotes: 0

Ankur Singhal
Ankur Singhal

Reputation: 26077

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);
}

Upvotes: 0

DJ Burb
DJ Burb

Reputation: 2392

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.

Upvotes: 1

Related Questions