We were trying to fetch results from database via SQL
query using hibernate
which will return List<Object[]>
, if records are present. But later we want to convert it into a List<Integer>
. So instead of iterating through the Object[]
list and keep on adding to integer list, we tried something and the sample code is like
public class ListObjectArrayToListInteger {
public static void main(String[] args) {
Object[] ob1 = {1};
Object[] ob2 = {5};
Object[] ob3 = {9};
List objList = new ArrayList();
objList.add(ob1);
objList.add(ob2);
objList.add(ob3);
//Case - 1
List<Integer> intList = objList;
System.out.println(intList);
//Case - 2
List<Integer> intList = new ArrayList<Integer>();
intList.addAll(objList);
System.out.println(intList);
}
}
We are only trying to fetch one column from the query and that's why all the Arrays
are having only one element. Both Case-1 and Case-2 were executed separately and output was same in both case, it was something like this
[[Ljava.lang.Object;@3e25a5, [Ljava.lang.Object;@19821f, [Ljava.lang.Object;@addbf1]
In Case-1 intList
a type of List<Integer>
, is pointing to an object of List
with Object[]
s. We were expecting an Exception in run time because the data types are entirely different.
In Case-2 we are explicitly adding Object[]
s to List<Integer>
and without any exception it is giving an output which up to my knowledge is wiered.
- So can anybody explain why we are getting output like this?
- How a
List<Integer>
, which is expecting onlyIntegers
at all its locations, would hold a data like this[[Ljava.lang.Object;@3e25a5, [Ljava.lang.Object;@19821f]
? - Why would Java allow users to add data from a raw data list to a generic list. In my code if I make
Object[] ob1 = {1, 2, "3", "abc"};
it can be added tointList
asintList.addAll(objList);
which is allowed and runs smoothly.