Java how to add items directly to a class rather than having an array object

Viewed 64

I have an Array as part of a class and can add items to that, but I would like to add items directly to the Class itself. Is that possible?

public class Buttons {
    public Array<SimpleButton> buttons = new Array<SimpleButton>();
}

Then I can add items like this:

buttons.buttons.add(simpButton);

But I want to add items directly like this:

buttons.add(simpButton);
3 Answers

You can add an "Add" function to your class and utilize it via the class object

public class Buttons {
public Array<SimpleButton> buttons = new Array<SimpleButton>();

public void add(SimpleButton input){
      //Handle invalid input
      buttons.add(input);
}
}

So to use it you will do something like -

Buttons buttonObj = new Buttons();
buttonObj.add(SimpleButtonTmp); //SimpleButtonTmp -> SimpleButton Obj

Otherwise if you don't wanna go this route you can do the following -

public class Buttons extends Array<SimpleButton>

Then you can access all the functions directly

public static void main(String[] args)
{
Buttons myButton = new Buttons();
myButton.*AnyfunctionInArray();
}

If you are sure that your class basically acts as List, you can utilize the ForwardingList from Guava. As the name suggests, it will forward all calls to the obtained delegate() instance. This way, you don´t have to implement all methods youself and can only override specific methods.

public class ButtonList extends ForwardingList<SimpleButton> {

    private final List<SimpleButton> delegate = new ArrayList<>();

    @Override 
    protected List<SimpleButton> delegate() {
        return delegate;
    }

}

Since calls are forwarded by default, you can call any regular List method.

ButtonList list = new ButtonList();
list.add(new SimpleButton());
int size = list.size(); // 1

However, if your class does not act as a List, i would recommend to create the required delegate methods yourself. This will hide implementation and makes future changes easier. Of course, this can be a bit of work, but modern IDEs have support the create delegate methods for you.

References:

You could use ArrayList and extend all ArrayList Methods example:

import java.util.ArrayList;

public class Buttons extends ArrayList{
    public  ArrayList<String> buttons = new ArrayList<String>();

}

Main Class:

public class Main{
    public static void main(String[] args) {
        Buttons buttons = new Buttons();
        buttons.add("button 1");

        int i=0;
        while(i < buttons.size())
        {
            System.out.println(buttons.get(i));
            i++;
        }
    }
}
Related