Locations not the same?

Discussion in 'Plugin Development' started by The Fancy Whale, Aug 7, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    The Fancy Whale

    I am working on a plugin which requires that the config check to see if a sign's location is in the config. The sign's location is in the config but for some reason it returns false...
    Code to check the locations and log info for testing:
    Code:java
    1. Location loc = new Location(Bukkit.getServer().getWorld(Main.Signs.getConfig().getString(s + ".World")),
    2. Main.Signs.getConfig().getDouble(s + ".X"),
    3. Main.Signs.getConfig().getDouble(s + ".Y"),
    4. Main.Signs.getConfig().getDouble(s + ".Z"));
    5. Main.getPlugin().getLogger().severe("Config: " + loc.toString());
    6. Main.getPlugin().getLogger().severe("Sign: " + block.getLocation().toString());
    7. if (loc == block.getLocation()){
    8. Main.getPlugin().getLogger().severe("TRUE");
    9. bool = true;
    10. }

    In the console:
    Code:
    07.08 17:30:33 [Server] INFO [17:30:33 ERROR]: [TNT_Wars] Sign: Location{world=CraftWorld{name=world},x=-127.0,y=68.0,z=188.0,pitch=0.0,yaw=0.0}
    07.08 17:30:33 [Server] INFO [17:30:33 ERROR]: [TNT_Wars] Config: Location{world=CraftWorld{name=world},x=-127.0,y=68.0,z=188.0,pitch=0.0,yaw=0.0}
    As you can see the locations are the exact same, yet it still returns false... If you know what the issue si I'd love to hear it. Any help is greatly appreciated thanks!
     
  2. Offline

    xTigerRebornx

    The Fancy Whale Don't use == to compare non-primitives. Also, comparing Locations using Location#equals() uses extreme precision, so I'd recommend you compare the block x/y/z 's of each (location#getBlockX()/getBlockY()/getBlockZ())
     
  3. Offline

    Traks

    The == operator is used for memory address comparisons, while the equals(Object) method is used for logical comparisons. These logical comparisons can be implemented differently by every single class. So use #equals instead of the == operator, since you don't want to compare memory addresses, but want to test their logical equivalency.
     
    Zupsub likes this.
  4. Offline

    coasterman10

    As stated above, the == operator compares the memory address of the object, as Java stores all objects by reference. Only primitive types and enum constants should be compared by ==. Everything else should be compared by equals(), because there is no guarantee that the two similar objects are in fact the same object and not just twins.

    For locations, equals() is fine. Do know though that locations are compared with great precision and you may not always want to be comparing locations directly. For CraftBukkit, comparing locations is generally safe for block locations.
     
Thread Status:
Not open for further replies.

Share This Page