I have a class called Tenant and I loop over the creation of 10 of
these objects. But I want to name them
Tenant1
Tenant2
Tenant3 etc
How do I do that?
In the code here they are all being named tenant rather than tenant1
etc:
for (int i=0; i<10; i++) {
Tenant tenant = new Tenant(i);
}
I thought maybe converting the int to a string like
Integer number = i;
String numberstring = number.toString();
But how would I then add numberstring onto the name of the object?
Joshua Cranmer - 13 Oct 2007 16:09 GMT
> I have a class called Tenant and I loop over the creation of 10 of
> these objects. But I want to name them
[quoted text clipped - 3 lines]
>
> How do I do that?
You don't. You use arrays.
> for (int i=0; i<10; i++) {
> Tenant tenant = new Tenant(i);
> }
Try:
Tenant[] tenants = new Tenant[10];
for (int i=0; i<10; i++) {
tenant[i] = new Tenant(i);
}
instead.

Signature
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth
hwdoer01@gmail.com - 13 Oct 2007 16:59 GMT
import java.util.SortedMap;
import java.util.TreeMap;
public class Tenants
{
public static void main(String[] args)
{
String prefix = "Tenant";
SortedMap<String, Tenant> tenants =
new TreeMap<String, Tenant>();
for(int i = 0; i < 6; i++)
{
String name =
prefix + Integer.valueOf(i).toString();
tenants.put(name, new Tenant(i));
}
for(String str : tenants.keySet())
{
System.out.println(str + " " + tenants.get(str).value);
}
}
static class Tenant
{
int value;
Tenant(int v){value = v;}
}
}