How to add data to a collection in Java?
In Java, you can use the add() method to add data to a collection. The specific steps are as follows:
- Create a collection object, which can be a List, Set, or Map, etc.
- Create the data object to be added.
- Use the add() method of the collection object to add the data object to the collection.
The example code is shown below:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
String data1 = "Java";
String data2 = "Python";
String data3 = "C++";
list.add(data1);
list.add(data2);
list.add(data3);
System.out.println(list);
}
}
The output result is: [Java, Python, C++].
In the example above, we start by creating an ArrayList collection object called ‘list’, then we create three String type data objects named ‘data1’, ‘data2’, and ‘data3’. Next, we use the add() method of the list to add these three data objects to the collection. Finally, we use the System.out.println() method to print out the contents of the collection, showing that the three data objects have been successfully added.