How to reduce copy-pasting?
If I have a number of similar classes, say:
Integer i0;
Integer i1;
Integer i2;
Integer i3;
Integer i4;
Integer i5;
Integer i6;
Integer i7;
Integer i8;
Integer i9;
And wanted to avoid doing this:
i0 = 0;
i1 = 1;
i2 = 2;
i3 = 3;
i4 = 4;
i5 = 5;
i6 = 6;
i7 = 7;
i8 = 8;
i9 = 9;
I'm thinking of doing something similar to this to achieve the same result:
int cnt = 0;
for(classname : arrayOfClassNames {
classname = cnt++;
}
How do I do that?
[clarification] I appears I was misunderstood开发者_运维技巧. I was thinking more along the lines of having 10 separate classes still, not one array having 10 items.
Use an array or an ArrayList?
// using an array
Integer[] ints = new Integer[10];
for (int i = 0; i < 10; i++) {
ints[i] = i;
}
// using an array list
ArrayList<Integer> ints = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
ints.add(i);
}
Following on from your update, what you are looking to do can be achieved using
Class.forName(classname).newInstance();
However, I would suggest that whatever you save in time to code it, you will lose in readability and ease of maintenance, so you may find this a false economy.
Store them in an array:
Integer[] array = new Integer[10];
for(int i = 0 ; i < 10 ; i++){
array[i] = i ;
}
To get i9: array[9]
Use a java.util.Map<T, K>
:
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < 10; i++)
{
map.put("i" + i, i);
}
System.out.println(map);
System.out.println("i8: " + map.get("i8"));
A number of similar classes sounds like you want an Array:
Integer[] manyI = new Integer[] {0, 1, 2, ....};
Or you fill the Array with a loop:
Integer[] manyI = new Integer[10];
for (int i = 0; i < manyI.length; i++) manyI[i] = i;
精彩评论