将两个枚举值存储在HashMap中

时间:2016-01-21 07:07:39

标签: java enums hashmap

我想将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);

    }
}

1 个答案:

答案 0 :(得分:0)

在main方法中初始化hMap .. 通过这个链接,希望它会帮助你..

How do I store Enum types into a map?