Cindy Zhang
Cindy Zhang

Reputation: 19

What is the different between creating a list and inserting a value at the same time vs. in 2 steps?

I am trying to give value pre[1] to a new list by using List <Integer> list = new ArrayList(pre[1]);, but I got an empty list .

When I make this into 2 steps: first create an empty list1, then add pre[1] to my list1 , it works: list1 contains 2.

Can anyone tell me why? I was expecting the same result.

I was thinking List <Integer> list = new ArrayList(pre[1]); is creating a list, and initializing the value to pre[1], but is not working, what is the problem??

int[] pre =new int []{1,2,3};
List <Integer> list = new  ArrayList(pre[1]);

List <Integer> list1 = new  ArrayList();
list1.add(pre[1]);

Upvotes: 0

Views: 71

Answers (2)

Vikas
Vikas

Reputation: 7205

The constructor of ArrayList receives initialCapacity not the element. So in your case you are creating List with initialCapacity 2 i.e pre[1].

public ArrayList(int initialCapacity)

You may want to try List.of in java9

List.of(pre[1], pre[2]);

Upvotes: 0

GalAbra
GalAbra

Reputation: 5138

Please read the documentation of ArrayList's constructors.

TL;DR: There is no constructor that receives the new element(s) that the initialized ArrayList should contain.
The constructor that you're calling is the one that receives an integer as argument, which has its capacity defined according to the argument (i.e. pre[1] or 2 in your case).

Upvotes: 3

Related Questions