I am attempting to convert an ArrayList
of class SomeClass
to an ArrayList
of class Object
. This new ArrayList
of Object
will then be passed to a function. I currently have done the following:
// convert ArrayList<SomeClass> to generic ArrayList<Object>
Object[] objectArray = someClassList.toArray();
ArrayList<Object> objects = new ArrayList<Object>();
for (int i = 0; i < objectArray.length; i++) {
objects.add(objectArray[i]);
}
someFunction(objects);
public void someFunction(ArrayList<Object> objects) {
// do something with objects
}
Is there a more efficient or "standard" way of doing this? Is what I am doing "wrong" in the first place?
The purpose of converting it to ArrayList
of class Object
is that I have created an external library to process ArrayList
of generic Object
s.
Convert list To ArrayList In Java. ArrayList implements the List interface. If you want to convert a List to its implementation like ArrayList, then you can do so using the addAll method of the List interface.
Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.
If you are able to change the function's signature to taking an ArrayList<? extends Object> objects
or an ArrayList<?> objects
(or even better, List
instead of ArrayList
), you will be able to pass your ArrayList<SomeClass>
directly.
The reason an ArrayList<SomeClass>
is not an ArrayList<Object>
is that an ArrayList<Object>
would accept that you add()
any kind of Object
into it, which is not something you can do with an ArrayList<SomeClass>
. On the other hand, an ArrayList<? extends Object>
will allow you to retrieve elements from the list, but not add elements, so ArrayList<SomeClass>
can safely be assigned to it.
Since you created the external library, I think it would be easier to modify the function signature to accept lists of any type. This can be accomplished using the unbounded wildcard ?
:
public static void someFunction(List<?> objects) {
// whatever
}
Then you don't need to make any conversions to call it:
public static void main(String[] args) {
List<String> words = new ArrayList<>();
someFunction(words);
}
Also, unless you have a good reason not to, it would be better to accept any List
in someFunction
instead of limiting your input to ArrayList
s. This makes your code more flexible and easier to change in the future.
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