Use ArrayList in another class

Discussion in 'Spigot Plugin Development' started by drhopeness, May 3, 2017.

  1. It's my main class
    Code (Text):
    package Main;


    import Main.Event.DunyaDegistirme;
    import Main.Event.Farm;
    import Main.Event.Golem;
    import Main.Event.Join;
    import Main.komut.Bolge;
    import Main.komut.Sakla;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.logging.Logger;
    import org.bukkit.*;
    import org.bukkit.command.*;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.event.Listener;

    import org.bukkit.plugin.Plugin;
    import org.bukkit.plugin.PluginManager;
    import org.bukkit.plugin.java.JavaPlugin;

    import com.sk89q.worldedit.bukkit.WorldEditPlugin;

    import Main.Craftlar.Saat;

    public class Main extends JavaPlugin
        implements Listener
    {

        private FileConfiguration config;

       
       
        public void onEnable()
        {
            this.getConfig().options().copyDefaults(true);
            this.saveConfig();
            this.config = this.getConfig();
            Saat.craftSaat();
           
            getCommand("sakla").setExecutor(new Sakla(null));
            getCommand("goster").setExecutor(new Sakla(null));
            getCommand("park").setExecutor(new Bolge());
            //getCommand("ayarlar").setExecutor(new Gui(this));
            registerEvents();
            saveDefaultConfig();
           
            Logger logger = getLogger();
            logger.info("|---------------------------------------------------------------------|");
            logger.info("|-----------------------------Eklenti Aktif---------------------------|");
            logger.info("|---------------------------------------------------------------------|");
        }

        public boolean onCommand(CommandSender sender, Command cmd, String label, String args[])
        {
            Player p = (Player)sender;
            if(label.equalsIgnoreCase("tesreload") && p.hasPermission("teamenders.admin"))
            {
                reloadConfig();
                p.sendMessage(getConfig().getString("reloadmesaj"));
            }
            return true;
        }

        private void registerEvents()
        {
            PluginManager pm = getServer().getPluginManager();
            pm.registerEvents(new Farm(this), this);
            pm.registerEvents(new DunyaDegistirme(), this);
            pm.registerEvents(new Golem(), this);
            pm.registerEvents(new Join(), this);
        }

        public void onDisable()
        {
            Logger logger = getLogger();
            logger.info("|---------------------------------------------------------------------|");
            logger.info("|-----------------------------Eklenti Pasif---------------------------|");
            logger.info("|---------------------------------------------------------------------|");
            saveConfig();
        }
        public WorldEditPlugin getWorldEdit() {
            Plugin p = Bukkit.getServer().getPluginManager().getPlugin("WorldEdit");
            if (p instanceof WorldEditPlugin) return (WorldEditPlugin) p;
            else return null;
    }
       
    }
    it's listener class which i use arraylist
    Code (Text):
    package Main.Event;

    import java.util.ArrayList;
    import java.util.List;

    import org.bukkit.GameMode;
    import org.bukkit.entity.Player;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerJoinEvent;

    public class Join
        implements Listener
    {

       
        List<String> isim = new ArrayList<String>();
       
       

        public void onJoinEvent(PlayerJoinEvent event)
        {
            Player p = event.getPlayer();
            if(p.hasPlayedBefore() && !p.hasPermission("teamenders.admin"))
                p.setGameMode(GameMode.SURVIVAL);
        }
       
       
        public void onJoin(PlayerJoinEvent e){
            Player p = e.getPlayer();
           
            if(p.isOp()){
                if(isim.contains(p.getName())){
                    p.sendMessage("Op listesinde adın var");
                }else{
                    isim.add(p.getName());
                    p.sendMessage("Op listesine adın eklendi");
                }
            }else{
                isim.remove(p.getName());
            }
           
        }
    }
    and it's command class which i want to use arraylist
    Code (Text):
    package Main.komut;

    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;

    public class Op implements CommandExecutor{

        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
       
            Player p = (Player) sender;
            if(label.equalsIgnoreCase("ops")){
                if(p.hasPermission("teamenders.admin"))
                    p.sendMessage(//i want to isim arraylist here);
            }
           
           
            return false;
        }

    }
     
    how can i use isim array list in command class
     
  2. You also can save Player in a List so you can just make it like this:

    Code (Text):
    public static ArrayList<Player>() isim = new ArrayList<>();
    // add Player with isim.add(p);

    //In CommandClass
    if (Join.isim.contains(p)) {}
     
  3. You can do that, or you can create something called a "singleton instance." Look up what those are and how to make them, and then make a getter for that list.
     
  4. actually i mean when player writes /ops, player recieves ops list
     
  5. Or be a lazy fuck like me and make it static
     
    • Optimistic Optimistic x 5
    • Funny Funny x 1
  6. In your main class add the below given code under the public class part.
    Code (Text):
    private static Main main;
    Next, in the first line of your onEnable() add the following:
    Code (Text):
    main = this;
    After this, create a static getter method like this in your mainclass itself,
    Code (Text):
    public static Main getInstance(){
    return this.main;
    }
    Now, when you need to access anything from the main class (such as the list called isim) use the following:
    Code (Text):
    Main.getInstance().isim.whatever_you_want_todo;
    Congratulations! You have now learned how to make a singleton access class. This means that only one instance of the certain class is created to be used by other classes. Hopefully these instructions helped you solve your issue. Happy to be of help. :D
     
    • Informative Informative x 1
  7. Why all the staticness?
    Completely useless, and easily leads to static abuse for a newer developer like OP seems to be.
    You could pass your 'Main' instance through the constructor of your Listener class and create a getter (or do it the easy way and make it public.. but please don't).
     
  8. Ma dude, this isnt static abuse. That is a completely different case where you overuse static just because you are lazy. Singleton classes are not assosiated with static abuse since it is used to limit instances. You need to read up on singletons and its uses.
     
  9. I never said this was static abuse. I said it could lead to static abuse. Also, thanks for the last sentence, really appreciate it. Now, this is off topic, so may as well stop before we begin an unrelated conversation.

    EDIT: Well, I guess I take it I'm wrong, apologies. I've always avoided sharing data across classes via static variables, so I guess I also learned something here.
     
  10. Above isn't static abuse. It's completely fine and normal. I would assume your main is a singleton, so no problem having that static reference.

    EDIT:
    No it can't lead to it.

    EDIT2:
    Most people have methods like this for their singleton:

    Code (Text):
    private static Clazz i = null;

    public static Clazz getInstance() {
      if (i == null) {
        return new Clazz();
      }
      return i;
    }

    private Clazz() {
      i = this;
    }
    But since you know the onEnable runs when the plugin has been enabled, you don't need the constructor part.
     
    #10 ExpDev, May 3, 2017
    Last edited: May 3, 2017
    • Agree Agree x 1
  11. You can make the list static then get the list as Join.isim.
     
  12. @jetp250
    Now ,this is what could potentially lead the OP to static abuse later on xD
     
  13. Ah, yes. Also, thank you and @ExpDev for clearing up my misunderstanding with the singletons, definitely going to read about this a bit more than what I had.

    Now, again, we're offtopic. Way too tired to even try to help right now, hopefully someone else will if OP still needs help.
     
  14. Mas

    Mas

    Or maybe you could take some time to learn the language instead of suggesting bad habits for others to follow, and possibly reconsider whether your self-proclamation of being a Java developer is correct.
     
  15. Learned it very well :) Why is this a bad habit?
     
    • Funny Funny x 1
  16. Mas

    Mas

    I highly doubt you learnt the language well at all if you're thinking you may aswell make everything static because why not :p
    Relearning it would be a good idea.
     
  17. Well then, what is the problem with making a field static?
     
  18. Mas

    Mas

    It's static abuse. The whole point of Object Oriented languages is to do things the OO way. Using static keyword just because you want to access a field is definitely static abuse, and if you still don't understand why this is bad, please take time to learn the language. It will help.

    In this case you should make the 'isim' object in the 'Join' class private and create a getter in the list class, then pass an instance of the 'Join' class to the other classes which need to access the list.

    These: may help you understand:
    Objects: https://docs.oracle.com/javase/tutorial/java/javaOO/objects.html
    What static does: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
     
  19. the proper way to do this is indeed not by directly accessing the field, my mistake. However, from my understanding of the situation, there is no need at all to use non-static field.
    Java features are made to be utilized, there is no "bad features" or "features that we need to limit our use of", just features that doing one thing or another. As programmers, we need to know those features and where we should and shouldn't use them.
     
    • Funny Funny x 1
  20. Well, let's say it is public static. Now every program have full access to modifying this field, without reflection. This can be dangerous, and cause your program to corrupt and produce unwanted results.

    Let's say you have a plugin:
    Code (Text):
    public class CoolPlugin extends JavaPlugin {

      // nothing wrong here innit?
      public static List<String> plzDontTouchMe = new ArrayList<String>();

    }
    Oh my lord, here come's another plugin!
    Code (Text):
    public class CoolerPlugin extends JavaPlugin {

      // try and touch me. u wont be able (without some wizardry reflection of course)
      private List<String> cantTouchMe = new ArrayList<String>();

      // I am defiantly cooler
      public void ruinCoolPl() {
        CoolPlugin coolPl = (CoolPlugin) Bukkit.getPluginManager().getPlugin("CoolPlugin");
        if (coolPl == null) {
          return; // to scared are ya?
        }

        // I'm gonna ruin your data!! Muwhahaha
        coolPl.plzDontTouchMe = null; // I just set your list to null, and you don't even know! Expect unexpected results in ur silly program
      }

      // However, I do allow you to properly access my object:
      public List<String> getList() {
        return cantTouchMe;
      }
    }
    Now, we could set it to private static, but what would be the point of that, unless it is for a very good reason? Your Main class is defiantly singleton (unless you have a constructor there which would be odd), and you can just access it OOP like that instead.

    Examles kind of silly, but really do hope you get the point. CoolPlugin would throw a NullPointerException if it were to try and use the list.