java 如何初始化自定义类对象数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38946025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialize array of custom class objects?
提问by Zulqurnain Jutt
It sounds easy but i've been trying to do it for quite sometime, I want to initialize my custom class object array using curly braces
听起来很简单,但我已经尝试了很长时间了, I want to initialize my custom class object array using curly braces
Here is the failed example:
这是失败的例子:
class:
班级:
class Tranforminfo{
int left;
int top;
int right;
int bottom;
float rorate;
public Tranforminfo(int left, int top, int right, int bottom, float rorate) {
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
this.rorate = rorate;
}
}
Usage: (not correct)
用法:(不正确)
// attempt 1
Tranforminfo somedamn = new Tranforminfo[]{(1,2,3,4,5),(6,4,3,5,6)};
// attempt 2
Tranforminfo somedamn = new Tranforminfo[]{{1,2,3,4,5},{6,4,3,5,6}};
// attempt 3
Tranforminfo somedamn = new Tranforminfo[]((1,2,3,4,5),(6,4,3,5,6));
No luck so far help appreciated , i am coding in android(JAVA)
到目前为止没有运气帮助赞赏,我在android(JAVA)中编码
回答by jisecayeyo
There is some ways to do it:
有一些方法可以做到:
Transforminfo[] somedamn =
new Transforminfo[] { new Transforminfo(1,2,3,4,5),
new Transforminfo(6,4,3,5,6) };
Transforminfo[] somedamn =
{ new Transforminfo(1,2,3,4,5), new Transforminfo(6,4,3,5,6) };
First you create Transforminfo
array link, then add new Transforminfo
elements into.
首先创建Transforminfo
数组链接,然后向其中添加新Transforminfo
元素。
It's like Integer []array = {1, 2, 3}
, but you have to use constructor to create Transforminfo
elements.
就像Integer []array = {1, 2, 3}
,但是您必须使用构造函数来创建Transforminfo
元素。
One more example to understand array of object creating. All way is equal.
另一个例子来理解对象创建的数组。所有的方式都是平等的。
String array[] = { new String("str1"), new String("str2") };
String[] array = { new String("str1"), new String("str2") };
String array[] = new String[] { new String("str1"), new String("str2") };
String[] array = new String[] { new String("str1"), new String("str2") };
回答by Regedit
Transforminfo[] somedamn = {new Transforminfo(1,2,3,4,5), new Transforminfo(1,2,3,4,5)};
Transforminfo[]
is creating a link to an Array of Transforminfo and with the {...}
you create the actual Array (a special java syntax and actually the shortest one)
Transforminfo[]
正在创建一个指向 Transforminfo 数组的链接,然后{...}
创建实际的数组(一种特殊的 java 语法,实际上是最短的语法)
What you did was: You created a link to a Transforminfo Object and tried to set this link to an Array Object
您所做的是:您创建了一个指向 Transforminfo 对象的链接并尝试将此链接设置为一个数组对象