My method is trying to find a certain card with a suit and a value previously described in enums. My original code is:
public int find(Suit s, Value v) {
for(int i=0; i<numCards; i++) {
if(cards[i].getSuit() == s && cards[i].getValue() == v) {
return i;
}
}
return -1;
}
cards was an array and I've already converted it to an array, but how do I modify the code to apply to an ArrayList? Is there a method I should be using or would HashTables help me?
Maybe this (assuming it's cards that is the arraylist):
public int find(Suit s, Value v) {
for(int i=0; i<cards.size(); i++) {
if(cards.get(i).getSuit()==s && cards.get(i).getValue()==v) {
return i;
}
}
return -1;
}
This should traverse through every element in the ArrayList
for cards
You should really never use arrays. They are inherently less flexible and reliable.
You should have a Card class like this:
public class Card implements Comparable<Card> {
public int compareTo(Card other) { return this.value - other.value;}
}
Then have
List<Card> cards;
Notice I am specifying ArrayList or LinkedList .. just List.
Then you can just use
int index = Collections.binarySearch(cards,new Card(...));
Implementing a for loop is just not the way to go.
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.