To print an ArrayList in Java, you can use several methods depending on your needs:
Direct Print Using
System.out.println():
Simply pass theArrayListdirectly toSystem.out.println(). This uses thetoString()method of the list and prints elements in a readable format.ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); System.out.println(list); // Output: [Apple, Banana]Using a For-Each Loop:
Ideal for printing each element on a new line.for (String item : list) { System.out.println(item); }Using a Traditional For Loop:
Useget()andsize()to iterate by index.for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); }Using Java 8 Streams (
forEach):
Clean and functional style, especially with lambda expressions.list.forEach(System.out::println);Using
String.join()(for single-line output):
Join elements with a delimiter like comma or space.System.out.println(String.join(", ", list)); // Output: Apple, BananaUsing
Collectors.joining()(Java 8+):
Similar toString.join(), useful in stream pipelines.String result = list.stream().collect(Collectors.joining(", ")); System.out.println(result);
For custom objects, ensure the class overrides toString() to display meaningful output; otherwise, you'll see default hash codes like Object@12345.
list.toString() is good enough.
The interface List does not define a contract for toString(), but the AbstractCollection base class provides a useful implementation that ArrayList inherits.
Answer from oldo on Stack Overflowlist.toString() is good enough.
The interface List does not define a contract for toString(), but the AbstractCollection base class provides a useful implementation that ArrayList inherits.
Add toString() method to your address class then do
System.out.println(Arrays.toString(houseAddress));
Videos
If I have the following code:
List<Integer> arr = new ArrayList<>(); arr.add(1); arr.add(2); arr.add(3); System.out.println(arr);
it prints out [1, 2, 3] to the console. Since arr is an object, shouldn't println() print the memory location of the object? Why does it print out each value instead?