Home > Enterprise >  Why does this ArrayList 'add' operation not add the new element?
Why does this ArrayList 'add' operation not add the new element?

Time:09-29

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

CodePudding user response:

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.

  • Related