Reputation:
If you have an ArrayList (named al
in this case), and you're looking to get the first five elements of the list as variables, you could do this:
String x1 = al.get(0);
String x2 = al.get(1);
String x3 = al.get(2);
String x4 = al.get(3);
String x5 = al.get(4);
However, using a for loop, is there a way you could do something like this instead:
for (int i = 1; i < 6; i++){
String namer = "x" + i.toString();
String [value of String 'namer'] = al.get(i-1);
}
Or is there a completely different method that is much more efficient?
Upvotes: 4
Views: 150
Reputation: 3231
If you are trying to literally create variables on the local stack dynamically you would need to use reflection both ways (if it is even possible, which I don't think it is), otherwise it wouldn't compile then I would stick with the rule of thumb of Don't optimize unless you need to
If you are trying to create a reference to variables you can use a map
Map variables = new HashMap();
for (int i = 1; i < 6; i++) {
variables.put("x"+i, al.get(i-1));
}
Then you can access like this
variables.get("x1"); //or x2,x3,x4
Upvotes: 2
Reputation: 12678
"Perhaps" you don't want to do this in practice, but you could (all from within your program):
String x1 = ...
) as a proper class to a *.java
file (with adjustments as needed)*.class
file*.class
file into your program and use itUpvotes: 1
Reputation: 2652
Dynamic metaprogramming is not possible in java. Depending on what you are trying to achieve, there would be various options.
If you are trying to work in batches of 5 items, the cleanest solution is the one you are using now. If code duplication bothers you as much as it bothers me, then you are looking into Views in Java Collections Framework, specifically the "View of a portion of a collection" section:
List<String> nextFive = list.subList(5, 10);
Upvotes: 5
Reputation: 6268
Why don't you just iterate through the ArrayList and break when you have reach the correct number of variables?
int i = 0;
for (Object obj : al) {
if (i > 5) { break; }
results.append(obj); // append the first five elements to the result
}
This, to my knowledge, is the quickest way to do it, since I believe the get()
method is O(n). So expliciting writing a get()
would prompt n! calls for the first n objects.
Upvotes: 1
Reputation: 1103
You can have a String
array of size 6 and do the following:
String[] str = new String[6];
for(int i=0; i<str.length; i++)
a[i] = al.get(i);
Upvotes: 3