我正在尝试创建一个Hashmap
来为我执行查找。但是,当我运行此测试代码时,输出为空。我认为这应该与钥匙的存储性质有关,但我并不积极。也许这是一个类似的怪癖,就像var1 == var2
不等于它们,除非它们指向内存中的相同对象,而是必须使用var1.equals(var2)
?为什么这个HashMap.get返回null?
有两个类来测试这个。
TestCard.java
import java.util.HashMap;
public class TestCard {
// HashMap for SpecialK Lookup
private static HashMap<Card, Integer> specialKLookup = new HashMap<Card, Integer>();
// Constructor
public TestCard(){
}
public static void main(String[] args) {
Card[] cards = new Card[3];
cards[0] = new Card((short)12, (short)0);
cards[1] = new Card((short)0, (short)1);
cards[2] = new Card((short)5, (short)2);
/* Build SpecialK Lookup HashMap.
* Ace of Spades = 0
* Ace of Hearts = 1
* Ace of Diamonds = 2
* Ace of Clubs = 3
* ...
* Two of Clubs = 51
*/
Integer specialKCounter = 0;
for(int i=12;i>=0;i--){
for (int j=0;j<4;j++){
specialKLookup.put(new Card((short)i, (short)j), specialKCounter++);
}
}
System.out.println(specialKLookup.get(cards[0]));
}
}
Card.java
public class Card{
private short rank, suit;
private static String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
private static String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
//Constructor
public Card(short rank, short suit){
this.rank = rank;
this.suit = suit;
}
// Getter and Setters
public short getSuit(){
return suit;
}
public short getRank(){
return rank;
}
protected void setSuit(short suit){
this.suit = suit;
}
protected void setRank(short rank){
this.rank = rank;
}
}
它还必须按合同执行“equals”。 – 2011-05-20 22:36:23