views:

144

answers:

6

in java can you have an array of variables?
if so what is the syntax?

here's an example if your confused:

varint[] ArrayOfVariablesThatAreInts = new varint[#] 

or

var[] ArrayofVariables = new var[#]

is something like this legal?

+1  A: 

To create an array of ints for example you would use:

int[] array = new int[size];

Where size is how big you want the array to be.

Binary Nerd
A: 

In java you can have arrays of a specific type (like string, int or any object). You can use this array positions to store variables if you want to store them in an array. Or alternatively you can create an object array which can store variables of different types. The length of the array needs to be pre defined and if that doesn't suit you,you can use any cooleciton like ArrayList

Fazal
+1  A: 

Sure. You can do something like: String[] arrayOfStrings = new String[10];

jebcor
+6  A: 

Yes you can use:

Foo[] arrFoo = new Foo[10];
arrFoo[0] = new Foo();
..

Or if you dont want to define a fix size, you can use an ArrayList:

List<Foo> arrFoos = new ArrayList<Foo>();
arrFoos.add(new Foo());
..
Prine
what is meant by Foo?
David
@David: Foo is like a generic way to say: "Fill in the blank with your own type"
OscarRyz
@David: an abstract term representing "something": http://en.wikipedia.org/wiki/Foobar
BalusC
Foo would be a class you create. But it could be anything for the first example (including primitive datatypes). In the second example with the ArrayList it cant be a primitive datatype.
Prine
+1  A: 

Not really.

You can have an array of int values though:

int[] intArray = new int[100]; // array to hold 100 int's

But you can't use them as variables, you'll have to use them as values.

intArray[0] = 512;// set's the first element in the array to 512


int someIntVariable = intArray[0]; // get the first element in the array ( 512 ) .

Arrays are fixed size ( once allocated can't shrink or grow ) to do that you should use a List ( variable size ) of ints:

List<Integer> list = new ArrayList<Integer>(); // Integer is a wrapper for int 
list.add(512);
list.add(1024);

int x = list.get(0);// get the first element in the list ( 512 ) 
OscarRyz
A: 

I'm not sure if this is what you mean by a array of variables but see if this is what your looking for.

import java.util.ArrayList;

public class StackQuestion {

private static int random1 = 1;
private static int random2 = 2;

public static void main(String [] args){

    ArrayList a1 = new ArrayList();
    a1.add(random1);
    a1.add(random2);

    System.out.println(a1.get(0));
    System.out.println(a1.get(1));


}

}

KunGor