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];
        }
    }
}
4
  • 1
    Instead of compareTo, why not use indexOf to find the existing elements Commented Jun 7, 2017 at 7:20
  • 2
    Why not using Set? Commented Jun 7, 2017 at 7:23
  • Why not use Java Collection objects instead of an array? Example Commented Jun 7, 2017 at 7:23
  • I had been out of touch with Java for years now. But I believe I used indexOf sometime back. Hava a look here stackoverflow.com/questions/4962361/… Commented Jun 7, 2017 at 7:25

3 Answers 3

2

Try this:

birdArray = new HashSet<String>(Arrays.asList(birdArray)).toArray(new String[0]);
Sign up to request clarification or add additional context in comments.

5 Comments

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];
just put above code at place of your comparison for loops.
and add this lines in imports ---> import java.util.HashSet; import java.util.Arrays;
: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.
ya, HasSet can not have duplicates as you need.
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.

1 Comment

I think i need a bit more resarch never heard of set or hashset aha.. but thank you
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);

1 Comment

ahh i understand what you mean now, i like first option ill try and think aha

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.