Skip to content
Advertisement

Why does this ArrayList ‘add’ operation not add the new element? [closed]

When I run this code I expect an ArrayList with one element, the String “Hi”, to be added to the ArrayList at the 0th index. When I print the element at the 0th index I don’t get “Hi”, rather I get true. I don’t know how to interpret that result.

package dataTypes;

import java.util.ArrayList;

public class DataTypes {

    public static void main(String[] args) {
        ArrayList myUnsafeArrayList =  new ArrayList();
        myUnsafeArrayList.add("hello");
        myUnsafeArrayList.add(100);      
        myUnsafeArrayList.add("end");
        System.out.println("Before add: " + myUnsafeArrayList.get(0));
        
        myUnsafeArrayList.add(0, ((new ArrayList()).add("Hi")));
        System.out.println("After add: " + myUnsafeArrayList.get(0));
    }
}

Here is the output I get:

Before add: hello
After add: true

Advertisement

Answer

This is what you are looking for:

public class DataTypes {

    public static void main(String[] args) {
        ArrayList myUnsafeArrayList =  new ArrayList();
        myUnsafeArrayList.add("hello");
        myUnsafeArrayList.add(100);      
        myUnsafeArrayList.add("end");
        System.out.println("Before add: " + myUnsafeArrayList.get(0));
        
        myUnsafeArrayList.add(0, Arrays.asList("Hi"));
        System.out.println("After add: " + myUnsafeArrayList.get(0));
    }
}

The reason being that with myUnsafeArrayList.add(0, ((new ArrayList()).add("Hi"))); you are saying “add to index 0 of myUnsafeArrayList the result of ((new ArrayList()).add("Hi"))“. If you check the reference documentation the add(E element) returns a boolean and that is why you actually get true instead of Hi.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement