Reputation: 2339
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?
Upvotes: 0
Views: 958
Reputation: 51030
You can use an ArrayList
of arrays of Object
s:
e.g.
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.
Upvotes: 3
Reputation: 19027
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.
Upvotes: 0
Reputation: 2832
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.
Upvotes: 1