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+'sList.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 useadd()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, useset(int index, E element)to replace the value at a specific position. Just make sure the index is between0andlist.size() - 1(valid existing positions):list.set(0, "updated first item"); // Replaces the first elementBatch-add elements
UseaddAll()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 (likenullor 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, useCollections.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 needset()at all—just useadd()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

