HashMaps

Discussion in 'Plugin Development' started by Divinity Realms, Feb 15, 2015.

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

    Divinity Realms

    How can I make a hashmap with a Player, & a Location then refer back to it and edit it l8r on? Heres a bit of code that might help out:
    Code:
    package me.extendedhorizons;
    
    import java.util.HashMap;
    
    import org.bukkit.Location;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.block.Action;
    import org.bukkit.event.player.PlayerInteractEvent;
    import org.bukkit.plugin.java.JavaPlugin;
    
    public class Main extends JavaPlugin
    {
        HashMap<Player,Location> portal = new HashMap<Player,Location>();
    
    @EventHandler
    public void onItemRightClick(PlayerInteractEvent event)
    {
        Action a = event.getAction();
        Player player = event.getPlayer();
        Location location = event.getPlayer().getLocation();
        if(a == Action.RIGHT_CLICK_BLOCK || a == Action.RIGHT_CLICK_AIR)
        {
            if(portal.containsKey(player))
            {
                player.teleport(portal.get(location));
            }else{
                player.sendMessage("You have not setup your first location yet!");
            }
        }
    }
    @Override
    public void onEnable(){
        System.out.println("Portals has been enabled");
       
    }
    @Override
    public void onDisable(){
        System.out.println("Portals has been disabled");
    }
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args)
    {
        Player player = (Player) sender;
       
        if(cmd.getName().equalsIgnoreCase("setportal1"))
        {
            portal.put(player, player.getLocation());
        }
        return true;
    }   
    }
     
  2. Offline

    SuperOriginal

  3. Offline

    iBecameALoaf

    First of all, I suggest not using player objects in hashmaps because they can lead to memory leaks. Instead, either use the player's UUID, or the player's name. Otherwise, your code should work correctly, except for the fact that you never registered your events.
     
  4. Offline

    teej107

    You're leaving a lot information out of that statement. If you remove the player when they leave, a memory leak won't be caused by your plugin. Using a WeakHashMap is an easy way to prevent leaks.
     
    xTrollxDudex likes this.
  5. Offline

    xTrollxDudex

    As long as you don't store the same reference somewhere else!
     
    teej107 likes this.
Thread Status:
Not open for further replies.

Share This Page