Vectors
Hi
What I want to do is have an object
Code_id.....Code_Name..... Color
1.....One.....Red
2.....Two.....Green
3.....Three...Blue
These at the moment are in a vector of vectors
[[1,One,Red],[2,Two,Green],[3,Three,Blue]]
I want to be able to reference the object say when a value is passed in 1 need to be able to get One and Red any ideas how to retrieve and store these so that I can access them this way.
Any help really appreciated
Thanks
Ys
Here's a more complete example:
import java.util.Hashtable
...
Hashtable ht = new Hashtable();
Vector v1 = new Vector();
v1.add("One");
v1.add("Red");
Vector v2 = new Vector();
v2.add("Two");
v2.add("Green");
Vector v3 = new Vector();
v3.add("Three");
v3.add("Blue");
ht.put("1", v1);
ht.put("2", v2);
ht.put("3", v3);
Vector first = (Vector) ht.get("1");
Wouldn't it be better to build a hashtable of "things", like this?
public class Thing
public int codeId;
public String codeName;
public String color;
public Thing(int codeId, String codeName, String color) {
this.codeId = codeId;
this.codeName = codeName;
this.color = color;
}
}
then in your main code:
t1 = new Thing(1, "One", "Red");
t2 = new Thing(2, "Two", "Green");
t3 = new Thing(3, "Three", "Blue");
Hashtable list = new Hashtable();
list.put(t1.codeId, t1);
list.put(t2.codeId, t2);
list.put(t3.codeId, t3);
Thing t = (Thing)list.get(1);
System.out.println(t.codeName + " " + t.color);
which should print out:
One Red
yes this is definately a better approch..just take care that
rather than
list.put(t1.codeId, t1);
u do
list.put(new Integer(t1.codeId), t1);
or simply keep
public Integer codeId //rather than int.
as Hashtable key value needs to be an object.
same logic while retriving back...
Thing t = (Thing)list.get(new Integer(1));
regards,
amit agrawal.
Of course, using the example code provided by darrelln, you could also subclass Hashtable so that you can get an object back no matter whether the user passes you a code id, a code name, or a color string...
public Class thingHash extends java.util.Hashtable
{
public void add(Thing newThing)
{
add( newThing.codeId, newThing );
add( newThing.codeName, newThing );
add( newThing.color, newThing );
}
}
now in your main code you can simply take an Object as an argument and still retrieve the other two properties of the object.
--David