117

I have an ArrayList that contains Address objects.

How do I print the values of this ArrayList, meaning I am printing out the contents of the Array, in this case numbers.

I can only get it to print out the actual memory address of the array with this code:

for(int i = 0; i < houseAddress.size(); i++) {   
    System.out.print(houseAddress.get(i));
}  
11
  • do you want the address location in memory? Commented Feb 13, 2012 at 18:20
  • sorry, i don't understand what you mean. the arraylist is storing the address pointing to the array, and i want to print the contents of the array, but I don't know how to go about it. Commented Feb 13, 2012 at 18:27
  • I tried to reword the question to make it clearer. Commented Feb 13, 2012 at 18:28
  • By Address, he mean House address. I think. Commented Feb 13, 2012 at 18:30
  • 1
    Please, just give us the declaration of the houseAddress variable, and some sample code for the elements that it contains. Commented Feb 13, 2012 at 18:35

24 Answers 24

146

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The same output is print by System.out.println(list);
list is houseAddress here: Arrays.toString(houseAddress.toArray())
AbstractCollection already overrides toString() to print the contents of its elements. So, just list.toString() prints the toString() of all its elements. This is true for all collections.
29

Add toString() method to your address class then do

System.out.println(Arrays.toString(houseAddress));

2 Comments

This would only work for an array, not an array list. You can not provide houseAddress as an argument for Arrays.toString() because it is not of type Array.
in my opinion looping is only possible wayout here , if anyone knows better option please share.
26

From what I understand you are trying to print an ArrayList of arrays and one way to display that would be

System.out.println(Arrays.deepToString(list.toArray()));

Comments

9

since you haven't provide a custom implementation for toString() method it calls the default on which is going to print the address in memory for that object

solution in your Address class override the toString() method like this

public class Address {

int addressNo ; 
....
....
...

protected String toString(){
    return Integer.toString(addressNo);
}

now when you call

houseAddress.get(i)  in the `System.out.print()` method like this

System.out.print( houseAddress.get(i) ) the toString() of the Address object will be called

Comments

9

You can simply give it as:

System.out.println("Address:" +houseAddress);

Your output will look like [address1, address2, address3]

This is because the class ArrayList or its superclass would have a toString() function overridden.

Hope this helps.

Comments

8

assium that you have a numbers list like that

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

if you print the list

//method 1
// Conventional way of printing arraylist
for (int number : numbers) {
    System.out.print(number);
}

//method 2
// Lambda Expression to print arraylist
numbers.forEach((Integer value) -> System.out.print(value));

//method 3
// Lambda Expression to print arraylist
numbers.forEach(value -> System.out.print(value));


//method 4
// Lambda Expression (method reference) to print arraylist
numbers.forEach(System.out::print);

Comments

5

Are you saying that ArrayList is storing addresses of arrays because that is what is returning from the toString call, or because that's actually what you're storing?

If you have an ArrayList of arrays (e.g.

int[] arr = {1, 2, 3};
houseAddress.add(arr);

Then to print the array values you need to call Arrays.deepToString:

for (int i = 0; i < houseAddress.size(); i++) {
     System.out.println(Arrays.deepToString(houseAddress.get(i)));
}

Comments

4
public void printList(ArrayList<Address> list){
    for(Address elem : list){
        System.out.println(elem+"  ");
    }
}

1 Comment

This is not different from OPs current code. The problem remains.
3

I am not sure if I understood the notion of addresses (I am assuming houseAddress here), but if you are looking for way a to print the ArrayList, here you go:

System.out.println(houseAddress.toString().replaceAll("\\[\\]", ""));

Comments

3

Since Java 8, you can use forEach() method from Iterable interface.
It's a default method. As an argument, it takes an object of class, which implements functional interface Consumer. You can implement Consumer locally in three ways:

With annonymous class:

houseAddress.forEach(new Consumer<String>() {
    @Override
    public void accept(String s) {
        System.out.println(s);
    }
}); 

lambda expression:

houseAddress.forEach(s -> System.out.println(s));

or by using method reference:

houseAddress.forEach(System.out::print);

This way of printing works for all implementations of Iterable interface.
All of them, gives you the way of defining how the elements will be printed, whereas toString() enforces printing list in one format.

Comments

3

Simplest way to print an ArrayList is by using toString

List<String> a=new ArrayList<>();
    a.add("111");
    a.add("112");
    a.add("113");
    System.out.println(a.toString());

Output

[111, 112, 113]

1 Comment

I donot think toString is required in this case. ArrayList overrides AbstractCollection class and hence it will take care of printing the values
3

Put houseAddress.get(i) inside the brackets and call .toString() function: i.e Please see below

for(int i = 0; i < houseAddress.size(); i++) {
    System.out.print((houseAddress.get(i)).toString());
}

2 Comments

@Mr.Goose i do not get your question quite clear, what do you mean?
call to .toString() is redundant.
2

This helped to me:

System.out.println(Arrays.toString(codeLangArray.toArray()));

Comments

2
 public static void main(String[] args) {
        List<Moyen> list = new ArrayList<Moyen>();
        Moyen m1 = new Moyen();
        m1.setCodification("c1");
        m1.setCapacityManager("Avinash");
        Moyen m2 = new Moyen();
        m2.setCodification("c1");
        m2.setCapacityManager("Avinash");
        Moyen m3 = new Moyen();
        m3.setCodification("c1");
        m3.setCapacityManager("Avinash");

        list.add(m1);
        list.add(m2);
        list.add(m3);
        System.out.println(Arrays.toString(list.toArray()));
    }

Comments

2

You can use an Iterator. It is the most simple and least controvercial thing to do over here. Say houseAddress has values of data type String

Iterator<String> iterator = houseAddress.iterator();
while (iterator.hasNext()) {
    out.println(iterator.next());
}

Note : You can even use an enhanced for loop for this as mentioned by me in another answer

1 Comment

p.s. it is least controvercial because you are not doing any unnecesary conversions over here like converting ArrayList to Array and then converting it to string to print it
1

if you make the @Override public String toString() as comments, you will have the same results as you did. But if you implement your toString() method, it will work.

public class PrintingComplexArrayList {

public static void main(String[] args) {
    List houseAddress = new ArrayList();
    insertAddress(houseAddress);
    printMe1(houseAddress);
    printMe2(houseAddress);
}

private static void insertAddress(List address)
{
    address.add(new Address(1));
    address.add(new Address(2));
    address.add(new Address(3));
    address.add(new Address(4));
}
private static void printMe1(List address)
{
    for (int i=0; i<address.size(); i++)
        System.out.println(address.get(i));
}

private static void printMe2(List address)
{
    System.out.println(address);
}

}

class Address{ private int addr; public Address(int i) { addr = i; }

@Override public String toString()
{
    Integer iAddr = new Integer (addr);
    return iAddr.toString();
}

}

Comments

1

You can even use an enhanced for loop or an iterator like:

for (String name : houseAddress) {
    System.out.println(name);
}

You can change it to whatever data type houseAddress is and it avoids unnecessary conversions

Comments

0

Make sure you have a getter in House address class and then use:

for(int i = 0; i < houseAddress.size(); i++) {   
    System.out.print(houseAddress.get(i)**.getAddress()**);
}

1 Comment

Welcome to Stack Overflow. Please review the How to Answer section and edit your question accordingly.
0

you can use print format if you just want to print the element on the console.

for(int i = 0; i < houseAddress.size(); i++) {   
    System.out.printf("%s", houseAddress.get(i));
}  

Comments

0

Assuming that houseAddress.get(i) is an ArrayList you can add toString() after the ArrayList :

for(int i = 0; i < houseAddress.size(); i++) {   
    System.out.print(houseAddress.get(i).toString());
} 

A general example:

ArrayList<Double> a = new ArrayList();
a.add(2.);
a.add(32.);
System.out.println(a.toString());
// output
// [2.0, 32.0]

Comments

0

This is a simple code of add the value in ArrayList and print the ArrayList Value

public class Samim {

public static void main(String args[]) {
    // Declare list
    List<String> list = new ArrayList<>();

    // Add value in list
    list.add("First Value ArrayPosition=0");
    list.add("Second Value ArrayPosition=1");
    list.add("Third Value ArrayPosition=2");
    list.add("Fourth Value ArrayPosition=3");
    list.add("Fifth Value ArrayPosition=4");
    list.add("Sixth Value ArrayPosition=5");
    list.add("Seventh Value ArrayPosition=6");

    String[] objects1 = list.toArray(new String[0]);

    // Print Position Value
    System.err.println(objects1[2]);

    // Print All Value
    for (String val : objects1) {
        System.out.println(val);
      }
    }
}

Comments

0

JSON

An alternative Solution could be converting your list in the JSON format and print the Json-String. The advantage is a well formatted and readable Object-String without a need of implementing the toString(). Additionaly it works for any other Object or Collection on the fly.

Example using Google's Gson:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

...
public static void printJsonString(Object o) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    /*
     * Some options for GsonBuilder like setting dateformat or pretty printing
     */
    Gson gson = gsonBuilder.create();
    String json= gson.toJson(o);
    System.out.println(json);
}

Comments

0
  1. Add toString() method to your class
  2. houseAddress.forEach(System.out::println);

Comments

0

Consider using an "Enhanced for loop" I had to do this solution for a scenario in which the arrayList was coming from a class object

changing the String datatype to the appropriate datatype or class object as desired.

ArrayList<String> teamRoster = new ArrayList<String>();

// Adding player names
teamRoster.add("Mike");
teamRoster.add("Scottie");
teamRoster.add("Toni");

System.out.println("Current roster: ");

for (String playerName : teamRoster) {
   System.out.println(playerName);
   // if using an object datatype, you may need to use a solution such as playerName.getPlayer()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.