Java: HashMap.get returns null

2019-08-09 01:03发布

问题:

I am programming a socket server in Java for an MMORPG in AS3. I have some problems with strange behaviour of HashMap.get(byte[]). What things could cause the following problem?

I don't use any serialization system, I send bytes and both client and server knows what to do with what bytes of the received bytes. The first request the client makes is asking the server to create a playing session. The server will generate a random session token as byte[] with 8 entries and adds the token to the HashMap. The response will be 9 bytes long. The first one defines the response type (in this case byte '+' which means "You have been accepted. Here is your token.") and byte 2-9 are the token. The client must store the token and append it to any further request (This concept can be compared with PHP sessions).

This is the code for adding the client to the HashMap:

byte[] token = Util.generateToken();

// f is ResultSet entry of JDCB SQL query return value
Client client = new Client(f.getInt("id"), token);
Core.clients.put(token, client);

// I display client.token instead of token to make sure client != null      
Log.log("User " + f.getString("name") + " has logged in with session token " + Util.getHexString(client.token) + ".");

Log:

[01:50:30] User has logged in with session token 92:B7:F8:C6:4B:53:17:3A.

These are some debug lines that will displayed at any further request:

// Show (byte[]) Token as Hex String, 8 bytes long
Log.soc("Token: " + Util.getHexString(buffer.getBytes(1, 9)));

// Show all keys in (HashMap<byte[], client>) Core.clients
int it = 0;
for (byte[] b : Core.clients.keySet())
Log.soc("Key Core.clients #" + StringUtils.leftPad(String.valueOf(++it), 2, '0') + " = " + Util.getHexString((b)));

// Display availability bool to make sure
Log.soc(Core.clients.containsKey(buffer.getBytes(1, 9)));

// Get Core.clients value where key = Token
Log.soc("Client: " + Core.clients.get(buffer.getBytes(1, 9)));

Log:

[01:51:09] Token: 92:B7:F8:C6:4B:53:17:3A

[01:51:09] Key Core.clients #01 = 92:B7:F8:C6:4B:53:17:3A

[01:51:09] false

[01:51:09] Client: null

So, how could I find out what's going wrong?

回答1:

A HashMap uses hashCode() and equals() to find the entry from a given key. And a byte array will only ever be equal to itself. It won't be equal to another byte array, even if this other byte array has the same length and the same bytes. You should wrap the arrays inside a Key class which override equals() and hashCode() to make that work.