这是代码:
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}));
}
}
Run Code Online (Sandbox Code Playgroud)
我正在做的只是在地图中查找某些内容,但是我收到了一个错误:
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)
Run Code Online (Sandbox Code Playgroud)
数组只等于它们自己.这意味着将它们用作地图中的键将无法正常工作:
map.get(new byte[] {(byte) 1, (byte) 0})
Run Code Online (Sandbox Code Playgroud)
将始终返回null.
您需要创建一个包含两个字节字段的类,equals()并hashCode()正确覆盖它,并将该类用作映射的键.