0

At one point it compares array(1)compareto(array(1)) is this a problem? Amount birds is the amount of elements in array. I am trying to remove duplicate string in the array. Is it fixable or should i re approach.

for (i = 0; i <= amountBirds - 1; i++)
{
    for (x = 1; x <= amountBirds; x++)
    {
        duplicate = birdArray[i].compareTo(birdArray[x]);

        if (duplicate == 0)
        {
            birdArray[i] = birdArray[x];
        }
    }
}
Prabhav
  • 447
  • 3
  • 17
JC101
  • 1
  • 1
    Instead of `compareTo`, why not use `indexOf` to find the existing elements – Saurabh Tiwari Jun 07 '17 at 07:20
  • 2
    Why not using `Set`? – NiVeR Jun 07 '17 at 07:23
  • Why not use Java Collection objects instead of an `array`? [Example](https://www.mkyong.com/java/how-to-count-duplicated-items-in-java-list/) – Jacob Jun 07 '17 at 07:23
  • I had been out of touch with Java for years now. But I believe I used `indexOf` sometime back. Hava a look here https://stackoverflow.com/questions/4962361/where-is-javas-array-indexof – Saurabh Tiwari Jun 07 '17 at 07:25

3 Answers3

2

Try this:

birdArray = new HashSet<String>(Arrays.asList(birdArray)).toArray(new String[0]);
Prabhav
  • 447
  • 3
  • 17
  • Hi I actually set birdArray as a global variable, im not exactly sure how i should word that, here it is: public static String[] birdArray = new String[50]; – JC101 Jun 07 '17 at 07:32
  • just put above code at place of your comparison for loops. – Prabhav Jun 07 '17 at 07:35
  • and add this lines in imports ---> import java.util.HashSet; import java.util.Arrays; – Prabhav Jun 07 '17 at 07:41
  • :o it did something ill keep working at it thank you, it basically removed one of the elements in the array and also has a blank array element. But at same time does not accept duplicates if i enter one. – JC101 Jun 07 '17 at 07:48
  • ya, HasSet can not have duplicates as you need. – Prabhav Jun 07 '17 at 07:53
2

Try Set or LinkedHashSet . Convert your arraylist into Set , It will automatically remove the duplicate from List as Set does not allow Duplicate value. but Remember it is a Collection rather than a List.

Abhilash Arjaria
  • 142
  • 2
  • 10
2

Either you can include a if check before using compareTo method

if ( i != x ) {
        duplicate = birdArray[i].compareTo(birdArray[x]);
}

Or you can use Set in Java Collection library. This approach does not allow duplicate entries to be inserted. So at the time of insertion itself, you can avoid the duplicates.

Or you keep the birdArray as it is. And use a Set as a mediator to insert and remove the duplicates.

Set<String> birdSet = new LinkedHashSet<String>(); //to keep the order of the birds
for (i = 0; i < amountBirds; i++)
{
    birdSet.add (birdArray[i]);
}
birdArray = Arrays.copyOf(birdSet.toArray(), birdSet.size(), String[].class);
idarak
  • 126
  • 6