-
help with Hashtable
Hi i have a small problem. Im using a hashtable to store data and a class for the objects.. So i can create an object from the class and put it in the table....but the problem is that im using a loop to do it.
Here ill show u what i have:
for(int j=0;j<4;j++){
if(j==0){
name=h;
}
if(j==1){
dep=h;
}
if(j==2){
sal=h;
}
if(j==3){
date=h;
}
id++;
EmployeeX hid= new EmployeeX(name,dep,sal,date);
myHashtable.put(id,hid);
}
EmployeeX hid= new EmployeeX(name,dep,sal,date);
there is my problem right there.. it will add the first one..but i it loops again it will add the new one in the same class def and just overide it. I need to have it so that variable of EmployeeX changes each time.
For example if it were hid1 the first time then hid2 two...the problem is how do i get the vairable to change like that each time i loop?.
Thx..mind u the loop may not work..this is only part of the code i just need to know how to get the variable to change each time.
-
Hmm ... ?
Why do you allocate and store a new object on each loop iteration ? As I
can read this (pseudo ?) code it will not overwrite on each iteration, it
will create a new object and map it to a new key in the hashtable on each
iteration.
As I see it you could just as well allocate the object before the loop
(as a default uninitiated object), go through the loop and use setter methods
in the object (that you will have to implement) for the values,
and map the object into the hastable after the loop.
eschew obfuscation
-
Try to set the object in Hashtable this way
I think the following code meets your requirement...
import java.util.Hashtable;
public class Test {
public static void main( String[] a ){
Hashtable myHashtable = new Hashtable();
int id=1;
for(int j=0;j<4;j++){
id++;
myHashtable.put( String.valueOf(id),new Emp( "kar "+j) );
}
System.out.println ( "The h--- >"+myHashtable);
}
}
class Emp {
String name;
public Emp(){}
public Emp ( String name ) {
this.name = name;
}
public String toString() {
return ">> "+name+"\n";
}
}
Cheers...
Karthikeyan G
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks