Search code examples
javaarraylistminecraftbukkit

Spigot - Save Blocks that are not full represented by a BlockState - Java


I tried to program something like a "undo"-command. Maybe you know it from WorldEdit. For the saved Blocks I have a ArrayList<BlockState>, but if try to save a Chest, Sign, etc it doesn't work. Of course I could add a extra List for Chests ArrayList<Chest> and for Signs ArrayList<Sign> and for Droppers ArrayList<Furnace> ....

Is there a better and easier way to do this?

Thank you for your help and sorry for my bad English ;)


Solution

  • I'm not sure if I understand your question correctly, but you can define an inteface, let's say you call it CommonInterface, and have all your classes (BlockState, Chest, Sign ...) implement this interface. Then you can have one object of the type List<CommonInterface> (e.g.: List<CommonInterface> list = new ArrayList<>()) and save all your objects in this list.

    Note: when you get an object from the list, you need to check the run-time type of that object so that you know how to operate with it.

    Example:

    CommonInterface ci = list.get(0);
    if(ci instanceof BlockState){
       // do something ...
    }
    else if(ci instanceof Sign){
       // do something else ... 
    }
    ...
    

    Here's another example:

    import java.util.ArrayList;
    import java.util.List;
    
    public class TestGenerics
    {
       class A implements CommonInterface
       {
           public String say()
           {
               return "I'm A";
           }
       }
    
       class B implements CommonInterface
       {
           public String hi()
           {
               return "I'm B";
           }
       }
    
       class C implements CommonInterface
       {
           public String getName()
           {
               return "I'm C";
           }
       }
    
       interface CommonInterface
       {
    
       }
    
       public List<CommonInterface> get()
       {
           A a = new A();
           B b = new B();
           C c = new C();
           List<CommonInterface> ci = new ArrayList<>();
           ci.add(a);
           ci.add(b);
           ci.add(c);
           return ci;
       }
    
       public static void main(String[] args)
       {
           TestGenerics tg = new TestGenerics();
           List<CommonInterface> list = tg.get();
           for(CommonInterface ci : list){
               if(ci instanceof A){
                   System.out.println(((A)ci).say());
               }
               else if(ci instanceof B){
                   System.out.println(((B)ci).hi());
               }
               else if(ci instanceof C){
                   System.out.println(((C)ci).getName());
               }
            } 
          }
      }