简体   繁体   中英

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);

根据您提供的代码的理解,您需要使用tower.get(1)等,而不是tower.add(1)等。

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 and 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

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 tower.add(1); //Adds 1 to the ArrayList tower.add(2); //Adds 2 to the ArrayList

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM