Possible Duplicate:
How do I remove repeated elements from ArrayList?
I want to replace a duplicate number (if any) that i store in an ArrayList. I obtianed the numbers for a Random variable. Here is the class.
import java.util.*;
public class RandomNumbers {
// instance variables
private ArrayList<Integer> randomNumberList = new ArrayList<Integer>();
private Random randomNums = new Random();
public RandomNumbers(){
// generating and adding random numbers to the list
for (int i=0; i<MemoryGame.totalAnswers; i++)
randomNumberList.add(randomNums.nextInt(32));
System.out.println("Numbers in the list: " + randomNumberList);
System.out.println("");
}
public ArrayList<Integer> getRandomNumbers(){
return randomNumberList;
}
}
My school book tells me how to add,remove and retrieve a number, but not how to replace one that is duplicated.
thanks.
If you are not limited to
ArrayList, use aHashSet<Integer>instead (or better yet, a LinkedHashSet).HashSet<Integer>will garantee you not to have duplicated values in the collection,LinkedHashSet<Integer>will do the same and also preserve the ordering the the items.If you insist on having an
ArrayList, then do this :Also, if
MemoryGame.totalAnswers == 32, then you can speed up this process with a random list instead :** Update **
Since
MemoryGame.totalAnswers == 8, forget the last snippet. I’m leaving it there if anyone would happend to need it. You can skip the use of aSetentirely by folllowing pst‘s suggestion :