Is it possible to use a variable when naming an object?
Thanks for reading my question. I ap开发者_如何学编程ologize if this seems like an easily searchable question, but searching for anything with variable, object, and java turns up anything and everything.
Here is what I would like to do:
BankCheck = check(variable int here) = BankCheck(params here);
So that I can create check1000, then check1001, check1002 and so on.
Any suggestions?
Thank you!
EDIT:
Here is what I used:
ArrayList<Check> check = new ArrayList<Check>();
And the this to add each new object to the array.
check.add(checkNum, new Check(details, amount));
Usually this is solved using arrays. so instead of
check101 , check102 , check103
you will have
check[0] , check[1] , check[2]
etc
If the numbers are not consecutive and not known ahead of time one can also use a hashtable
Not, that's not possible but you have two options
1.- Create and array to hold a variable number of checks:
BankCheck[] checks = new BankCheck[100];
That will let you store 100 checks. You can also use a list:
List<BankCheck> checks = new ArrayList<BankCheck>();
Which works almost the same, except you don't have a fixed number of checks.
2.- The other option is to create an small program to create this for you and then you just copy paste the output:
...
public static void main( String ... args ) {
for( int i = 0 ; i < 100 ; i++ ) {
System.out.printf("BackCheck check%d = new BankCheck();%n");
}
}
But unless you're trying to do something really advanced ( or stupid ) you really will use option #1 most of the times.
I hope this helps
You have two choices here.
The first option, which I believe correct for your situation, is to declare an array and iterate through it:
final int checkCount = 10000; // Actual count to be filled in by you. My guess is 10k.
BankCheck[] checks = new BankCheck[checkCount];
for (int i = 0; i < checks.length; ++i) {
// It's not clear from your question exactly what should go here, but here is a guess.
checks[i] = check(params);
}
The second option is to code-gen the code if you really need to have a few thousand variables with different names.
In this case you probably want to use an Array.
BankCheck[] check = new BankCheck[100]; //100 objects
Then
check[0]
is the first object etc.
Alternatively, you may use a map if the check numbers are important.
Map<Integer, BankCheck> check = new HashMap<Integer, BankCheck>();
Then:
check.put(1008, ABankCheckObject);
will put the check 1008 in that location and can be accessed by:
check.get(1008);
If you don't want to have a fixed upper limit, use the ArrayList class, which can expand as necessary.
精彩评论