Henry
Henry

Reputation: 1042

Type mismatch: cannot convert from boolean to int

I am have a little problem with small part of my code: it says

Type mismatch: cannot convert from boolean to int.

Can someone please help me out? My code is below:

ArrayList<Integer> tower = new ArrayList<Integer>();
int Kilo = tower.add(1);
int Jan tower.add(2);

Upvotes: 2

Views: 4393

Answers (3)

childofsoong
childofsoong

Reputation: 1936

The problem is with int Kilo = tower.add(1);. The add method returns a Boolean, which most people don't bother storing, because it always returns true. This is because the superclass of ArrayList, Collection, uses that boolean to say whether or not the collection was changed as a result (with ArrayList, it's always changed, but other collections may not have that be true). You're trying to store this boolean value into an int named 'Kilo', hence the problem.

Based on what you've said, I think you want the following:

tower.add(1); //Adds 1 to the ArrayList
int Kilo = 1; //Stores 1 into Kilo

Upvotes: 3

Mikey
Mikey

Reputation: 697

From what I understand from the code you provide, you need to use tower.get(1) etc. and not tower.add(1) etc.

Upvotes: 4

dclifford
dclifford

Reputation: 27

You only need to do the tower.add(1); and the tower.add(2);, unless you are also attempting to cast variables to the contents of the ArrayList. Just use: tower.add(1); //Adds 1 to the ArrayList tower.add(2); //Adds 2 to the ArrayList

Upvotes: 0

Related Questions