How to declare array of parameterized object in Java?

Viewed 76

I have declare PDPage with PDRectangle parameter

Float width = 8.5f;
Float height = 5f;
Float dpi = 72f;
PDRectangle size = new PDRectangle(width*dpi, height*dpi);
PDPage page = new PDPage(size);

but I want to declare multiple PDPage with custom PDRectangle size in an array.

Something like not exactly:

ArrayList<PDPage> page = new ArrayList<PDPage(size)>();
2 Answers

There's a difference between creating a list and initializing it's elements. The initialization of the list only cares about the generic class specification:

List<PDPage> page = new ArrayList<>();

You can then add multiple instances of PDPage with the custom size to it:

page.add(new PDPAge(size)); // This can be done multiple times, e.g. in a loop

As Mureinik states in his answer, you first have to instantiate the list,

ArrayList<PDPage> pages = new ArrayList<>();

before adding instances to it (e.g. ten times):

for(int i = 0; i < 10; i++) {
    pages.add(new PDPage(size))
}

If strictly necessary that all objects in the list have the same dimensions you could in theory create a subclass:

public class SpecialPDPage {
    private static final Float width = 8.5f;
    private static final Float height = 5f;
    private static final Float dpi = 72f;
    private static final PDRectangle size = new PDRectangle(width*dpi, height*dpi);

    public SpecialPDPage() {
        super(size);
    }
}

and then initialize the list and add objects as follows:

ArrayList<SpecialPDPage> pages = new ArrayList<>();
for(int i = 0; i < 10; i++) {
    pages.add(new SpecialPDPage())
}

Related