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.
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.
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 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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With