Hi, I'm a beginner in using Hashmap and there is something that is turning me crazy but should be very easy if I had the concepts clear.
I'm trying to use a HashMap to store some float (energy) values for each point in space represented by a coordinate(x,y,z) defined in a simple class that I call Coord3d.
I have apparently no problem in creating the hashmap and filling it up with the energy values for each coordinate.
My problem comes when I try to read the value for any given coordinate:
1.- If I use something like
coord= new Coord3d((float) 0.0, (float) 0.0, (float) 0.0);
energy= energyValues.get(coord);
I get a NullPointer exception in the "get"
2.- If I assign values directly as in:
coord.x= (float) 0.0;
coord.y= (float) 0.0;
coord.z= (float) 0.0;
energy= energyValues.get(coord);
The "get" function of the Hasmap does not return the energy value of the searched coordinate but instead it returns the last stored value.
Attached I send a very simple and short testcase that reproduces my problems.
Thanks for any help and best regards,
JBB
import java.util.HashMap;
public class testCaseHashMap {
public static void main(String[] args) {
HashMap<Coord3d, Float> energyValues;
energyValues = new HashMap<Coord3d, Float>(); //Must use Object Float instead of primitive data type float
Coord3d coord= new Coord3d(-20.0f, -20.0f, -20.0f);
float energy=0.0f;
float x = 0,y = 0,z = 0;
for(int incX=0; incX<2; incX++){
for(int incY=0; incY<2; incY++){
for(int incZ=0; incZ<2; incZ++){
x= (float) incX;
y= (float) incY;
z= (float) incZ;
energy= (float) x+y+z;
coord= new Coord3d(x, y, z);
energyValues.put(coord,energy);
System.out.println("x= "+String.valueOf(x)+" y= "+String.valueOf(y)+" z= "+String.valueOf(z)+" "+String.valueOf(energy));
}
}
}
// If I use new I get a NullPointerException
coord= new Coord3d((float) 0.0, (float) 0.0, (float) 0.0);
//If instead I set manually the values it doesn't produce an error but gets the last value instead of the one with matching key
coord.x= (float) 0.0;
coord.y= (float) 0.0;
coord.z= (float) 0.0;
energy= energyValues.get(coord);
System.out.println(String.valueOf(energy));
}
}
And the simple definition of the Coord3d class:
public class Coord3d {
/** Create a 3d coordinate.*/
public Coord3d(float xi, float yi, float zi){
x = xi;
y = yi;
z = zi;
}
public float x;
public float y;
public float z;
}