You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何给ArrayList添加不同值?随机选元素去重添加实现方法

Hey there! Let's break down your two ArrayList questions clearly, with practical code examples you can use right away.

问题1:如何向ArrayList中添加不同的值?

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 the contains() method to verify if the element already exists in the list before calling add():

    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, HashSet is 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);
    
问题2:如何避免随机选取时重复添加同一对象?

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:03:52