'Why am I getting a type error in this LeetCode solution?
For my solution in Leetcode, I am getting the following error. The question is : https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
Error :
Line 15: error: incompatible types: boolean cannot be converted to List<Boolean>
return result.add(false);
^
Line 18: error: incompatible types: boolean cannot be converted to List<Boolean>
return result.add(true);
^
2 errors
My code:
class Solution {
public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
List<Boolean> result = new ArrayList<Boolean>();
int max = 0;
for(int i=0; i<candies.length; i++) {
if(candies[i] > max) {
candies[i] = max;
}
}
for(int i=0; i<candies.length; i++) {
if(candies[i] + extraCandies > max) {
return result.add(false);
}
else {
return result.add(true);
}
}
return result;
}
}
Solution 1:[1]
You should remove the return before the result.add(...). Otherwise, you try to return the value you just added to the list, instead of returning the list itself like you want.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mira Weller |
