Im trying to add my anonymous objects from a class to a Hashtable. I created my Hashtable as my teacher wants but there is one problem. I have to get x and y values one of my Objects. But System cannot find x anyway.
public class HashDatastructure{
public static void main(String[] args){
java.util.Hashtable kreise = new java.util.Hashtable();
for(int i = 0; i < 6; i++){
kreise.put(new Integer(i), new Kreis(120, 120, 60));
}
System.out.println(kreise.get(3).toString() + " is 4. Object
and this Object's X Value: "
+ kreise.get(3).x + " || Y Value: ");
}
}
And here it is my Kreis Class:
public class Kreis extends Object{
public int x; //Mittelpunkt-x
public int y; // Mittelpunkt-y
public int radius;
public final double PI = 3.14159; //Constant Variable for pi
public static int kreisCounter = kreisZaehler();
public static int counter = 0;
public Kreis(int x, int y, int radius){
this.x = x;
this.y = y;
this.radius = radius;
kreisCounter();
}
private static int kreisZaehler(){
counter++;
return counter;
}
public void setRadius(int wert){
radius = wert;
}
public double getFlaeche(){
return radius * radius * PI;
}
public double getUmfang(){
return 2 * radius * PI;
}
}
I don't know what you mean by "anonymous objects," but you're using raw types, which is generally not a good idea. Instead, tell the compiler what kind of object kreis
contains:
java.util.Hashtable<Kreise> kreise = new java.util.Hashtable<>();
// ----------------^^^^^^^^---------------------------------^^
Then, the compiler will know that get
returns a Kreis
object, which has x
and such. (Side note: Probably better to make x
private and provide an accessor like getX
for it.)
More to explore in the Generics Java Tutorial.
If for some reason you have to use raw types, you can cast to Kreis
on retrieval:
// NOT recommended
System.out.println(kreise.get(3).toString() + " is 4. Object and this Object's X Value: "
+ (((Kreise)kreise.get(3)).getX() + " || Y Value: ");
// -----------------^^^^^^^^^-------------^-^^^^^^
(Note I'm assuming you make x
private and provide an accessor for it.)