Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass custom object to Arrays.asList

Tags:

java

arrays

Say I have a Person class and I am trying to create a list as;

Person p1 = new Person("first", "id1");         
Person p2 = new Person("dummy", "id1"); 
Person p3 = new Person("second", "id2");         
Person p4 = new Person("third", "id1");         
List<Person> asList = Arrays.asList(p1, p2, p3, p4); 

Now my question is instead of passing the indivdual Person objects to Arrays.asList()

can I pass a combined list, something like

List<Person> asList = Arrays.asList(combinedPersonObjs); 

I have tried many things, but am getting casting errors.

Please help

Note: The number of Person objects is dynamic.

like image 354
copenndthagen Avatar asked Jul 26 '12 09:07

copenndthagen


People also ask

Can we add elements to arrays asList?

asList() is not an ArrayList but just another List implementation. It is also a fixed-size list which means you cannot add or remove elements and it's backed by an array, which means any change in the array will reflect in the list as well.

What does arrays asList () do?

The asList() method of java. util. Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.

How is array asList () different?

How is Arrays. asList() different than the standard way of initialising List? Explanation: List returned by Arrays. asList() is a fixed length list which doesn't allow us to add or remove element from it.


1 Answers

Sure, you can do

Person[] combinedPersonObjs = { p1, p2, p3, p4 };
List<Person> asList = Arrays.asList(combinePersonObjs);

If you don't know the number of Person objects in advance, then presumably you don't have one variable identifier for each object. I suggest you simply do something like

List<Person> asList = new ArrayList<Person>();
for (int i = 0; i < numberOfPersons; i++)
    asList.add(new Person(ithName(i), "id" + i));
like image 114
aioobe Avatar answered Nov 03 '22 19:11

aioobe