Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2007

Tip: Looking for answers? Try searching our database.

very simple question about naming objects

Thread view: 
maths@tokyo.com - 13 Oct 2007 16:07 GMT
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;}
 }
}


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.