Pix81
Pix81

Reputation: 677

How to get distinct values from an arraylist?

I'm afraid I don't understand collections and data structures enough to process similar questions referring to a hash set. I currently have a loop that in a program that randomizes indexes within an array. The original array passed into the method consists of all prime numbers less than 1,000.

Not including the full program as it's part of a larger homework assignment.

My problem is that the if statement I created is printing out numbers repeatedly even though I thought I coded it to only print out the number if the number is already not in the array.

Can someone point out the mistake in my logic?

public static void shuffle(int[] intArray, String name)
{
    assert intArray != null : "null!";
    long seed = name.hashCode();
    Random random = new Random(seed);

    for(int i = 0; i < 1000; i++)
    {
        int random_m = random.nextInt(intArray.length);
        int random_n = random.nextInt(intArray.length);

        int temp = intArray[random_m];
        intArray[random_m] = intArray[random_n];
        intArray[random_n] = temp;

        int zeroIndex = intArray[0];
        List<Integer> myList = new ArrayList<Integer>();

        if(!myList.contains(zeroIndex))
        {
            System.out.println(zeroIndex);
        }
        myList.add(zeroIndex);
    }
}

Partial example of output:

5821 5821 5821 5821 5821 5821 5821 5821 5821 5821 5821 5821

Upvotes: 0

Views: 78

Answers (2)

some IT dood
some IT dood

Reputation: 78

Use int zeroIndex = intArray[i];

Hope you get it now :-)

Upvotes: 0

Adersh
Adersh

Reputation: 97

        List<Integer> myList = new ArrayList<Integer>();

This Line of Code Creates New memorySpace for myList Through every iteration , so every time you iterate through the loop the myList values will be reset .

So define myList outside the loop.

Upvotes: 4

Related Questions