简体   繁体   中英

How to declare array of parameterized object in Java?

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)>();

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 (eg 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())
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM