我想将socket.getSocket()
和socketStatus.getSocketStatus()
存储在HashMap
中。但是hMap.put(socket.getSocket(),socketStatus.getSocketStatus());
会抛出NullPointerException
。我该如何解决这个问题?
以下是我的两个班级:
SocketInfoMap.java
package vd.socket.map;
import java.util.HashMap;
import java.util.Map;
public class SocketInfoMap {
public enum Socket {
ONE("01"), TWO("02"), THREE("03"), FOUR("04"), FIVE("05"), SIX("06"), SEVEN("07"), EIGHT("08");
private static Map<Socket, String> sMap = new HashMap<Socket, String>();
private String socket;
private Socket(String socket) {
this.socket = socket;
}
public String getSocket() {
return socket;
}
static {
for (Socket socket : Socket.values()) {
sMap.put(socket, socket.getSocket());
}
}
}
public enum SocketStatus {
LIFTED(1), NOT_LIFTED(0);
private static Map<SocketStatus, Integer> stMap = new HashMap<SocketStatus, Integer>();
private int socketStatus;
private SocketStatus(int socketStatus) {
this.socketStatus = socketStatus;
}
public int getSocketStatus() {
return socketStatus;
}
static {
for (SocketStatus socketStatus : SocketStatus.values()) {
stMap.put(socketStatus, socketStatus.getSocketStatus());
}
}
}
private static Map<String, Integer> hMap = new HashMap<String, Integer>();
public SocketInfoMap(Map<String, Integer> hMap) {
SocketInfoMap.hMap = hMap;
}
public Map<String, Integer> gethMap() {
return hMap;
}
}
SocketMapTest.java
package vd.socket.map;
import java.util.Map;
import vd.socket.map.SocketInfoMap.*;
public class SocketMapTest {
private static Map<String, Integer> hMap;
public static void main(String[] args) {
SocketStatus socketStatus = SocketStatus.LIFTED;
Socket socket = Socket.TWO;
if ((socket == Socket.TWO) && (socketStatus == SocketStatus.LIFTED)) {
hMap.put(socket.getSocket(), socketStatus.getSocketStatus());
System.out.println(hMap);
} else
hMap.put(socket.getSocket(), socketStatus.getSocketStatus());
System.out.println(hMap);
}
}