![](/img/trans.png)
[英]Bulls and Cows game program Java. Null pointer exception error when running the program
[英]Null point exception when looking up a Map in java.
這是代碼:
import java.security.InvalidParameterException;
import java.util.HashMap;
import java.util.Map;
/**
* Created by IDEA on 13/06/15.
*/
public class ShiftCodes {
private final Map<byte[], Byte> shiftMap;
public ShiftCodes(int[][] collapseMatrix) {
shiftMap = new HashMap<byte[], Byte>();
for (int i = -128; i < 128; i++) {
for (int j = -128; i < 128; i++) {
byte b1 = (byte) i;
byte b2 = (byte) j;
byte[] k = new byte[] {b1, b2};
Byte v = new Byte(GenoBytes.genoByte(GenoBytes.collapse(
b1, b2, collapseMatrix)));
shiftMap.put(k, v);
}
}
}
public ShiftCodes() {
this(GenoBytes.defaultCollpaseMatrix);
}
public byte lookup(byte b1, byte b2) {
return shiftMap.get(new byte[] {b1, b2}).byteValue();
}
public byte[] lookup(byte[] bs1, byte[] bs2) {
if(bs1.length != bs2.length) {
throw new InvalidParameterException("bs1 and bs2 must be of the same length");
}
byte[] res = new byte[bs1.length];
for(int i = 0; i < bs1.length; i++) {
res[i] = lookup(bs1[i], bs2[i]);
}
return res;
}
public static void main(String[] args) {
ShiftCodes shiftCodes1 = new ShiftCodes();
ShiftCodes shiftCodes2 = new ShiftCodes(GenoBytes.antidiangonal);
// System.out.println(shiftCodes1.lookup((byte) 0b11, (byte) 0b01));
System.out.println((int) shiftCodes1.shiftMap.get(new byte[] {(byte) 1, (byte) 0}));
}
}
我所做的只是在地圖中查找某些內容,但出現錯誤:
Exception in thread "main" java.lang.NullPointerException
at vu.co.kaiyin.ShiftCodes.main(ShiftCodes.java:50)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
數組只等於它們自己。 這意味着將它們用作地圖中的鍵不會像您期望的那樣工作:
map.get(new byte[] {(byte) 1, (byte) 0})
將始終返回 null。
您需要創建一個具有兩個字節字段的類,並正確覆蓋equals()
和hashCode()
,並將該類用作映射的鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.