[ Generic list in java to hold any objects ]
I am new to Java. I want to make an array List which will be able to hold any objects. I am wondering how to achie this. I am trying to use Class, but I am not sure how do I get the object from that. Here is what I am tring to do
<T> List<T> ConvertToList(<Map <String, List<Long>>map, Class<T> clazz)
{
//I want to extract all values from the map and store into an object as refered
//by clazz and put that into list.
...
...
List<T> list = new ArrayList<T>();
}
Is it possible and if yes how to do that?
Answer 1
I believe the answer to your question is yes. To do this, use the following code
ArrayList<Object> arrayList = new ArrayList<>();
You can now add class that extends Object to the array list, I believe all classes do this implicitly.
Answer 2
A List
implementation can hold any type of Object
. This is because it employs generics. Keep in mind that an ArrayList
is only a wrapper for an array
of elements. It simply appears to manipulate the size of that array by redeclaring it behind the scenes. It's simple enough to replicate this functionality, as below:
public class MyList<T> {
T[] elements;
}
This can be initialised in a number of ways:
MyList<String> list = new MyList<String>();
MyList<MyList<Integer>> intList = new MyList<MyList<Integer>>();
And so, by definition, you can expose it as the raw type:
MyList myObjectList = new MyList();
But your IDE will complain, and this is a good thing. You should avoid dealing with the type Object
, and try to make it more specific, to avoid casting things all over the place.
Example - Writing a method signature to convert a Map
implementation to a List
implementation.
This one is a little more interesting, but follows the same principle. Let's say you want to create a single list from all the values
in a Map
.
public List<T> <K,T> mapToList(Map<K, T> map) {
List<T> list = new ArrayList<T>();
list.addAll(map.values());
return list;
}
NOTE: This was included so you can get a better idea of how generics work, and how Java deals with variable method arguments.