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

Java中如何为List赋值?循环创建List调用set方法遇问题求解

Hey there! Let's tackle your two Java List questions clearly and practically.

问题1:如何在Java中为List设置值?

There are a few common ways to populate or update a List, depending on your use case:

  • Initialize with fixed values upfront
    If you have a set of predefined elements, use Java 9+'s List.of() for a quick immutable list (note: you can't add/remove elements later). If you need a mutable list, wrap it in an ArrayList:

    List<String> immutableList = List.of("apple", "banana", "cherry");
    List<String> mutableList = new ArrayList<>(List.of("apple", "banana", "cherry"));
    

    For older Java versions, use Arrays.asList() and convert to an ArrayList to get full mutability:

    List<String> mutableList = new ArrayList<>(Arrays.asList("apple", "banana", "cherry"));
    
  • Add individual elements to an empty list
    Start with an empty list and use add() to append elements one by one. This increases the list's size each time:

    List<String> list = new ArrayList<>();
    list.add("first item");
    list.add("second item");
    
  • Modify existing elements with set()
    Once your list has elements, use set(int index, E element) to replace the value at a specific position. Just make sure the index is between 0 and list.size() - 1 (valid existing positions):

    list.set(0, "updated first item"); // Replaces the first element
    
  • Batch-add elements
    Use addAll() to bulk-add elements from another collection or array:

    List<String> anotherList = List.of("date", "elderberry");
    list.addAll(anotherList);
    // Or add from an array directly
    list.addAll(Arrays.asList("fig", "grape"));
    

问题2:循环中调用set()出错的原因及解决办法

The issue with your code is straightforward: when you create a new empty ArrayList<>() with List listOfString = new ArrayList<>();, its initial size is 0. The set() method can only modify existing elements—you can't set a value at an index that doesn't exist yet! This will throw an IndexOutOfBoundsException every time.

Here's how to fix it:

  • Fill the list first before using set()
    If you need to set a specific index, first populate the list up to that index with placeholder values (like null or a default string):

    int targetIndex = 3;
    List<String> listOfString = new ArrayList<>();
    // Fill the list to reach the target index
    for (int i = 0; i <= targetIndex; i++) {
        listOfString.add(null); // Placeholder
    }
    listOfString.set(targetIndex, "my desired value"); // Now this works!
    
  • Initialize a pre-sized list with default values
    If you know the exact size you need, use Collections.nCopies() to create a list filled with a default value, then convert it to an ArrayList:

    int neededSize = 5;
    List<String> listOfString = new ArrayList<>(Collections.nCopies(neededSize, null));
    listOfString.set(2, "hello"); // Directly modify the 3rd element (index 2)
    
  • Use add() instead if you're building the list in a loop
    If you're adding elements sequentially in a loop, you don't need set() at all—just use add() to append each value. The list will automatically grow as needed:

    List<String> listOfString = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
        listOfString.add("element " + i); // Adds elements one by one
    }
    

内容的提问来源于stack exchange,提问作者Gonzalo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:38:13