开发者

Creating Variables at Runtime in Java [closed]

开发者 https://www.devze.com 2023-01-24 02:23 出处:网络
Closed. This question needs details or clarity. It is not currently accepting answers. Want to improve this question? Add details and clarify the problem by editing this post.
Closed. This question needs details or clarity. It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post.

Closed 2 years ago.

开发者_运维知识库 Improve this question

In my code I have a pretty big loop and I need to create a new variable at the end of each iteration (integers). Is this possible? I read about a ScriptEngineManager class, but I'm not sure if this will be able to help. I suppose I could create a bunch of integers equal to 0, but I'm not exactly sure how many times I will need to create a new variable (it depends on the conditions of the loop). Hopefully this makes sense.


Use an array. In Javascript, place var results = [] before your loop and append results using results.push(value). In Java, you'll want to use an ArrayList. (Those are very different languages, by the way.)


Hopefully this makes sense.

Unfortunately, it doesn't.

In Java it makes no sense to create variables on the fly. It is extremely difficult to do, and once you have done it they are extremely difficult to use. (By contrast, it is easy to do in Javascript ...)

However, this just means that you need to do what you are trying to in a different way. For instance, the following does a computation in a loop and then saves the results in an (existing) ArrayList variable:

    List<Integer> results = ArrayList<Integer>();
    while (...) {
        // Do computation ...
        int result = ...
        results.add(result);
    }
    // Now we have all of the results in 'results'

Or, if you want to bind each of the results to a distinct name, you could do something like this:

    Map<String, Integer> results = HashMap<String, Integer>();
    while (...) {
        // Do computation ...
        String name = ...
        int result = ...
        results.put(name, result);
    }


Following is the way that i have implemented and helped me to fix my solution easily without much hurdles.

// Creating the array List

List accountList = new ArrayList(); 




for(int k=0;k < counter;k++){
        accountList.add(k, (String)flowCtx.getValueAt("transitId"+m));
}

Iterating the loop and adding the objects into the arraylist with the index.

//Retrieving the object at run time with the help of the index

String a = accountList.get(i));


No, It is not possible to declare variables in java at runtime. But java provides java.util.map, which can be used like in the example below. We can assume that the key is the variable name.

Map<String, Object> declareVariableRuntime= new HashMap<String, Object>(); declareVariableRuntime.put("variableName", new Object());

0

精彩评论

暂无评论...
验证码 换一张
取 消