Reputation: 1825
I have an ArrayList
, "list", that contains one value, true. However, when i write:
if (list.get(0)==true)
I get the error "incompatible operand types Object and boolean". Is ArrayList.get()
method always return object
? if so, how can I get the boolean
value?
thanks.
Upvotes: 1
Views: 8530
Reputation: 11117
If your list always contains booleans I suggest you type your arraylist as boolean
List<Boolean> list = ArrayList<Boolean> ();
And now you are able to do what you want to do:
if (list.get(0))
For information:
if (list.get(0)==true)
and if (list.get(0))
are identical.
if you cannot use generics you can cast
if((Boolean) list.get(0))
{
System.out.println("OK");
}
Upvotes: 5
Reputation: 342
You can try to create a var to verify if the "if" statement will be true like this:
for(int i = 0; i < aList.size();i++){
match = aList.get(i).equals("Red");
System.out.print(match);
}
The match variable will receive the Boolean value of this comparison.
Regards,
Otacon.
Upvotes: 2
Reputation: 10342
Yes, ArrayList stores objects and it cannot know the class, unless you use generics.
So you have two options: Generics or casting every "get".
With casting:
if ( ((Boolean)list.get(0))==true ) { ... }
With generics, declare list as:
List<Boolean> list= new ArrayList<>();
list.add(true);
if (list.get(0)) { // list.get(0)==true is unnecesary
...
}
Upvotes: 2