How do you set a variable equal to an array in Java. For example I have a class for input and a class for calculations which hold arrays. when I accept the user input from the input class how do I pass that variable into the array of my calculation class?
A:
You should look into varargs. Code sample below:
public MyClass method(String ...arg);
You can call this method as :
method("test1", "test2", "test3"); // with arbitrary number of values.
Or as
String[] test = something;
method(test);
fastcodejava
2010-02-27 06:53:50
double sample [] = { priceone, pricetwo,pricethree }Ok for exampl lets say I have array sample and I want to pass into array sample the variables of priceone pricetwo and pricethree. The variables are from an input class.
waterfalrain
2010-02-27 06:59:24
@water - You could simply do sample[0] = priceone; etc. That's if I understand you correctly.
fastcodejava
2010-02-27 07:01:53
@fastcodejava Thanks, that's what I was looking for.
waterfalrain
2010-02-27 07:06:47
A:
Unless you have strict requirements to use arrays, you should probably be using a Collection, like a List.
For example, if you're trying to manage an array of ints, you could instead do:
List<int> intList = new ArrayList<int>();
Then, if you really need the data in the form of an array, you can do:
intList.toArray();
Which would return an array holding the integer values in your list. Lists are easier to read and use.
Zachary
2010-02-27 06:58:47