简体   繁体   English

如何在Java中声明参数化对象的数组?

[英]How to declare array of parameterized object in Java?

I have declare PDPage with PDRectangle parameter我必须声明PDPagePDRectangle参数

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.但我想声明多重PDPage自定义PDRectangle大小的数组。

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:然后,您可以添加多个具有自定义sizePDPage实例:

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,正如 Mureinik 在他的回答中所说,您首先必须实例化列表,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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