Add a set of data and container printing to the container from the ground up in java-9.3
In this section, we will discuss how to add a set of data to the container and how to print the container.
1. Add a group of data to the container
The container can use addAll () to add a group of data to the container:
(1) Add another Collection
(2) Add an array
(3) Add a list separated by commas (,).
Package com. ray. ch09; import java. util. arrayList; import java. util. collection; import java. util. collections; public class Test {public static void main (String [] args) {Collection
Collection = new ArrayList
(); For (int I = 0; I <10; I ++) {collection. add (I);} Collection
Collection2 = new ArrayList
(); For (int I = 0; I <4; I ++) {collection. add (I);} collection. addAll (collection2); // Add a CollectionCollections. addAll (collection, 1, 2, 3); // Add a comma-separated list Integer [] array = {1, 2, 3, 4}; Collections. addAll (collection, array); // Add an array }}
As you can see from the code above, the parameters after Collections. addAll are a set of variable parameters, so it can accept a list or an array.
The following is another method: Arrays. asList
package com.ray.ch09;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;public class Test {public static void main(String[] args) {Integer[] array = { 1, 2, 3, 3, 4 };List
list = (ArrayList
) Arrays.asList(array);List
list2 = Arrays.
asList(array);Collections.addAll(list, 1, 2, 3);Collections.addAll(list2, 1, 2, 3);}}
It can also add a group of data to the container, but note that it has a limitation, because its underlying implementation is implemented by arrays, so when adding and deleting data, Collections is required. addAll method.
2. Container Printing
package com.ray.ch09;import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;public class Test {public static void main(String[] args) {Collection
collection = new ArrayList
();for (int i = 0; i < 10; i++) {collection.add(i);}Arrays.toString(collection.toArray());}}
As you can see from the code above, the Arrays. toString method is generally used, but note that Collection must be converted to an array before printing.
Summary: This section briefly discusses how to add a set of data to a container and how to print the container.