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]. How can i do this?
You can use an ArrayList
of arrays of Object
s:
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:
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.
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<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.
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.
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.
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.