简体   繁体   中英

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

        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.

Use int zeroIndex = intArray[i];

Hope you get it now :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM