I wanted to make a method to check if I can see if each of my piles have 6 cards in it. This is my method
public boolean checkIfPileHasSixCards() {
map.put("tpile1", tpile1);
map.put("tpile2", tpile2);
map.put("tpile3", tpile2);
for (ArrayList<Card> value : map.values()) {
int size=value.size();
if(size==6) {
return true;
}
}
return false;
}
Is my logic correct, is there a more efficient way I can iterate over the values and check if each value (ArrayList) size is 6?
Returning true
inside the loop is not correct - this way, your method will return true
if any list in the map has six elements, not if all of them do. Instead, you should return false
if a list doesn't have six elements, and only return true
after you're done iterating the values:
for (List<Card> value : map.values()) {
int size = value.size();
if(size != 6) {
return false;
}
}
return true;
Note, by the way, that using Java 8's stream could make this snippet a lot cleaner. It won't be more efficient (it's still an O(n) operation in the worst case), but it will definitely be more concise:
return map.values().stream().allMatch(l -> l.size() == 6);
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.