Reputation: 13
I have an ArrayList of objects ArrayList<Object> arrList
containing wrapper classes for the various primitives as well as an array of type Parameter Parameter[] parameters
Both have the same number of elements. I would like to loop through the elements of parameters and compare that their types are the same as those in arrList.
I realise there are many ways of comparing an int with Integer.lang.Integer such as simply casting the int to an Integer and then comparing but my Parameter[] has ints, booleans, floats etc and my ArrayList has Integers, Floats, Booleans etc, so I am not always sure what the value will be. I don't think I really understand how primitives are represented. For example, I assumed the following statement would return true but it does not:
Boolean bool=true;
System.out.println(boolean.class==bool.getClass());
I have this the relevant bit of code:
for(int i=0; i<parameters.length; i++){
if(parameters[i].getType()==arrList.get(i).getClass()){
doSomething();
}
}
But the comparison always returns false even when it compares boolean.class to Boolean.getClass()
Thanks for any help/advice
Upvotes: 0
Views: 287
Reputation: 2922
You can use the static field TYPE
that every wrapper class has. (source)
for(int i=0; i<parameters.length; i++){
if(parameters[i].getType()==arrList.get(i).getClass().getField("TYPE").get(null)){
doSomething();
}
}
You could also compare the lowercase class names but you would have to handle int
and char
as special cases.
Alternatively you could create a Map<Class, Class>
between primitive classes and wrapper classes.
Upvotes: 1