如何给ArrayList添加不同值?随机选元素去重添加实现方法
Hey there! Let's break down your two ArrayList questions clearly, with practical code examples you can use right away.
ArrayList doesn’t block duplicate elements by default, so if you want to ensure you’re only adding unique values, you’ve got two straightforward options:
Manual check before adding
Use thecontains()method to verify if the element already exists in the list before callingadd():ArrayList<String> myList = new ArrayList<>(); String newElement = "Chicken"; // Only add if the element isn't already present if (!myList.contains(newElement)) { myList.add(newElement); }Use a Set for automatic deduplication
If your core goal is to maintain a collection of unique values,HashSetis built for this—it automatically ignores duplicates. You can convert it to an ArrayList later if you need ArrayList-specific functionality:// Start with a Set to guarantee uniqueness Set<String> uniqueSet = new HashSet<>(); uniqueSet.add("Chicken"); uniqueSet.add("Dinner"); uniqueSet.add("Chicken"); // This duplicate gets ignored automatically // Convert to ArrayList when needed ArrayList<String> uniqueList = new ArrayList<>(uniqueSet);
For your example where you’re picking from firstlist (["Chicken", "Dinner", "Noodles"]) to populate list2 without duplicates, here are two reliable approaches:
Approach 1: Track picked indices
Maintain a separate set to keep track of which indices you’ve already selected. Generate random indices until you get one that hasn’t been used yet:
import java.util.ArrayList; import java.util.HashSet; import java.util.Random; public class RandomUniquePick { public static void main(String[] args) { ArrayList<String> firstList = new ArrayList<>(); firstList.add("Chicken"); firstList.add("Dinner"); firstList.add("Noodles"); ArrayList<String> list2 = new ArrayList<>(); HashSet<Integer> usedIndices = new HashSet<>(); Random random = new Random(); // Keep picking until we've added all unique elements (or stop earlier if needed) while (usedIndices.size() < firstList.size()) { int randomIndex = random.nextInt(firstList.size()); if (!usedIndices.contains(randomIndex)) { usedIndices.add(randomIndex); list2.add(firstList.get(randomIndex)); } } System.out.println(list2); // Outputs a random, duplicate-free list } }
Approach 2: Use a temporary list to remove picked elements
Make a copy of firstlist, then remove elements from this temporary list as you pick them. This way, you’ll never pick the same element twice:
import java.util.ArrayList; import java.util.Random; public class RandomUniquePick2 { public static void main(String[] args) { ArrayList<String> firstList = new ArrayList<>(); firstList.add("Chicken"); firstList.add("Dinner"); firstList.add("Noodles"); // Create a temporary copy to modify ArrayList<String> tempList = new ArrayList<>(firstList); ArrayList<String> list2 = new ArrayList<>(); Random random = new Random(); while (!tempList.isEmpty()) { int randomIndex = random.nextInt(tempList.size()); // Remove the element from tempList and add it to list2 String pickedElement = tempList.remove(randomIndex); list2.add(pickedElement); } System.out.println(list2); // Outputs a random, duplicate-free list } }
This second approach is cleaner if you plan to move all elements from firstlist to list2—no extra index-tracking set required.
内容的提问来源于stack exchange,提问作者Ronald Woan

