How can Java output the elements in a collection?
To print elements in a collection in Java, you can loop through the collection elements and then use the System.out.println() method to print each element. Here are the specific steps:
- Import the java.util package to utilize collection classes.
import java.util.*;
- Create a collection object, for example an ArrayList:
List<String> list = new ArrayList<>();
- Add elements to the collection.
list.add("元素1");
list.add("元素2");
list.add("元素3");
- Iterate through the collection using a loop and print out each element.
for(String element : list) {
System.out.println(element);
}
The complete example code is as follows:
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("元素1");
list.add("元素2");
list.add("元素3");
for(String element : list) {
System.out.println(element);
}
}
}
Running the code above will output the elements in the set.
元素1
元素2
元素3