0

I'm trying to .put a pair into a linkedhashmap but when i put 2 or more the size never changes! When i iterate it i get every pair but in random order but the size stays 1. When i hard code the .put (example playerCoords.put(1,"test")) the size changes.

playerCoords = new LinkedHashMap<Integer, String>();

while (message[0] != "234124214") {
    message = (String[]) input.readObject();
    if (message[0] != null) {
        playerCoords.put(Integer.parseInt(message[0]), message[1]);
        output.writeObject(playerCoords);
        output.flush();
    }
}

EDIT: When i open the program 1 client connects to the server and his coords and port get written in the linkedhashmap (ex. 25565,"1 1 2") and then another joins (ex/ 25566, "1 2 1") and when I iterate i get both of these examples but the size still is 1!

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
kris
  • 1
  • 1
  • How do you check that the size never changes? – Sergey Kalinichenko Aug 28 '18 at 21:53
  • 2
    Please provide a [mcve]. Also, see [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – shmosel Aug 28 '18 at 21:54
  • System.out.println(playerCoords.size()); – kris Aug 28 '18 at 21:54
  • 3
    And where are you putting that code? Please post a full working example of what you describe so we can run it and see. – takendarkk Aug 28 '18 at 21:56
  • Also check [How do I compare strings in Java?](https://stackoverflow.com/q/513832/738746). – Bhesh Gurung Aug 28 '18 at 22:01
  • In order to trace the codes flow, we would need to know what `message` is. Because it depends on its content whether the `if` is entered or not (i.e. whether stuff is put into your map or not). We need a [mcve] (emphasis on **complete**) to answer the question. – Zabuzard Aug 28 '18 at 22:44

1 Answers1

1

You need to use the String method equals() for literal string comparisons, you can't use == or !=

while (message[0] != "234124214")

to

while (!message[0].equals("234124214"))

Improper placement of creating the LinkedHashMap would explain why you are getting a size of 1. You're overwriting the previous LinkedHashMap with another one of size 0 then adding a single entry, hence only ever seeing a size of 1.

playerCoords = new LinkedHashMap<Integer, String>();

Place the above code outside your looping of the messages

RAZ_Muh_Taz
  • 4,059
  • 1
  • 13
  • 26
  • 1
    Well, you *can*. But it usually doesn't do what people expect it does. It may be better to explain the difference (identity vs content). Or to flag as duplicate. – Zabuzard Aug 28 '18 at 22:42
  • Yes but thats not what i ask – kris Aug 28 '18 at 22:42