英文:
How to declare array of parameterized object in Java?
问题
我已经使用PDRectangle
参数声明了PDPage
:
Float width = 8.5f;
Float height = 5f;
Float dpi = 72f;
PDRectangle size = new PDRectangle(width*dpi, height*dpi);
PDPage page = new PDPage(size);
但我想要声明多个具有自定义PDRectangle
大小的PDPage
并放入一个数组中。
类似但不完全相同的方式如下:
ArrayList<PDPage> pages = new ArrayList<>();
PDRectangle customSize = new PDRectangle(customWidth * dpi, customHeight * dpi);
PDPage customPage = new PDPage(customSize);
pages.add(customPage);
英文:
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)>();
答案1
得分: 2
有在创建列表和初始化其元素之间有着区别。列表的初始化仅关注于通用类规范:
List<PDPage> page = new ArrayList<>();
然后,您可以添加多个具有自定义size
的PDPage
实例到其中:
page.add(new 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
答案2
得分: 1
如Mureinik在他的回答中所述,首先必须实例化列表:
ArrayList<PDPage> pages = new ArrayList<>();
然后再将实例添加到列表中(例如十次):
for(int i = 0; i < 10; i++) {
pages.add(new PDPage(size))
}
如果严格要求列表中的所有对象具有相同的尺寸,理论上您可以创建一个子类:
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);
}
}
然后初始化列表并按以下方式添加对象:
ArrayList<SpecialPDPage> pages = new ArrayList<>();
for(int i = 0; i < 10; i++) {
pages.add(new SpecialPDPage())
}
英文:
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())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论