0

Hi guys thanks for helping in advance this is not the real code it is just the idea i want to reach

for (int i = 1, i< some number ; i ++ )

float  [][] sts + i = new float[9][9];

The idea is to have 2 dimensional arrays with dynamic names initializing in a loop

sts1 sts2 sts3 . . . . .

4
  • Yeah you can't use dynamic names for variables in java, like you can in PHP. Just use array or ArrayList. Commented Jan 4, 2015 at 18:07
  • That's impossible I'm afraid. Just use a float[][][]. Commented Jan 4, 2015 at 18:07
  • If you want to keep reference names "sts"+i, one of the finest solutions is to use a HashMap<String, float[][]>. Eg yourMap.put("sts" + i, new float[9][9]); Commented Jan 4, 2015 at 18:10
  • possible duplicate of Assigning variables with dynamic names in Java Commented Jan 4, 2015 at 18:16

3 Answers 3

2

For your problem, where naming is sequential based on the value of i, an ArrayList could do the job as you can iterate over it.

However, a more general approach that enables you accessing your arrays by some String name (even if this was random and not sequential as in your case) would be to use a Map<String, float[][]>, where the key String of the Map is the name you have given to your array.

Map<String, float[][]> myMap = new HashMap<String, float[][]>();

for(int i = 0; i < someNumber; ++i)
{
    myMap.put("sts" + i, new float[9][9]);
}

then access each array by myMap.get(_aName_);

Sign up to request clarification or add additional context in comments.

1 Comment

Yes that would be an alternative to my solution. If the names have a particular meaning, then I would also use the HashMap version.
1

If you create every 2 dimensional array in the loop, then the variabl (like sts1) will only be local to the loop. So after the loop the variable is out of scope (but I think you want to use them after the loop, that's why you want different names). So to use the created variables, you have to use an array. And if you use an array, the question of naming ceases.

ArrayList<float[][]> l = new ArrayList<float[][]>();

for(int i = 0; i < someNumber; ++i)
{
    l.add(new float[9][9]);
}

1 Comment

thank you you are correct i will use this arrays globally to create time series
0

You can't create variable names dynamically in Java. Just do this

float[][][] sts = new float[someNumber][9][9];

Then you can use sts[0], sts[1] where you wanted to use sts1, sts2 etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.