What is the method for assigning values to a dynamic array in Java?

In Java, a dynamic array typically refers to the ArrayList class. To assign values to a dynamic array, you can use the add() method or the set() method.

  1. Use the add() method:
ArrayList<String> list = new ArrayList<>();

list.add("Value1");
list.add("Value2");
list.add("Value3");
  1. Use the set() method:
ArrayList<String> list = new ArrayList<>();

list.add(0, "Value1"); // 在索引0处添加元素Value1
list.set(1, "Value2"); // 将索引1处的元素替换为Value2
list.set(2, "Value3"); // 将索引2处的元素替换为Value3

When using the set() method, it is important to pay attention to the range of the index to ensure it does not exceed the size of the dynamic array.

bannerAds