[英]dynamic 2 dimensional array
I have a program that that creates a list of values. 我有一个可以创建值列表的程序。 (String, double, double, double ) I would like to store these values in an array, vector, or array that is array[x][4].
(字符串,双精度型,双精度型,双精度型)我想将这些值存储在数组,向量或数组为array [x] [4]的数组中。 How can i do this?
我怎样才能做到这一点?
You can use an ArrayList
of arrays of Object
s: 您可以使用
Object
数组的ArrayList
:
eg 例如
List<Object[]> list = new ArrayList<Object[]>();
list.add(new Object[]{"string", 2d, 1d, 0d});
Update : 更新 :
They can be printed as follows (since we know that the array elements are String
and Double
s: 可以按如下方式打印它们(因为我们知道数组元素是
String
和Double
:
for(Object[] row : list) {
System.out.println(row[0] + " " + row[1] + " " + row[2] + " " + row[3]);
}
But I do believe that it's a lot better to use a class here for OOP. 但我确实相信,在这里将类用于OOP会更好。
To keep it simple: 为简单起见:
Create Data Object class with 4 fields: 创建具有四个字段的数据对象类:
class MyDataObject {
String firstParameter;
double secondParameter;
double thirdParameter;
double fourthParameter;
}
Then store this object in List: 然后将此对象存储在List中:
List<MyDataObject> = new ArrayList<MyDataObject>();
if your class is present in the same java file (so it is in the same package) - you can avoid using accessors because of default package visibility access. 如果您的类存在于同一java文件中(因此它位于同一包中)-由于默认的包可见性访问,您可以避免使用访问器。
What if you create a class and declare those four fields within it and store the objects of that class into an ArrayList
as shown in the following example. 如果创建一个类并在其中声明这四个字段并将该类的对象存储到
ArrayList
中,该怎么办,如以下示例所示。
final class DemoClass
{
String str="";
double a;
double b;
double c;
public DemoClass(String str, double a, double b, double c)
{
this.str=str;
this.a=a;
this.b=b;
this.c=c;
}
public void doSomething()
{
//...
}
}
final public class Main
{
public static void main(String...args)
{
DemoClass dc=new DemoClass("SomeStrValue", 1, 2, 3);
List<DemoClass>list=new ArrayList<DemoClass>();
list.add(dc);
}
}
Would make it easier I think. 我认为这样会更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.