I'm confused about the need to case when using the getKey()/getValue() when using Map.
Here's the example that I wrote for Student class.
public class Student
{
int studentID;
String name;
double mark;
Student(int id, String n, double m)
{
studentID = id;
name = n;
mark = m;
}
public int getID()
{
return studentID;
}
public String getName()
{
return name;
}
public double getMark()
{
return mark;
}
}
import java.util.*;
public class StudentTest
{
public static void main(String[] args)
{
Student s1 = new Student(123, "Jane", 60.5);
Student s2 = new Student(456, "John", 76.5);
Student s3 = new Student(789, "Jim", 85);
int[] studentID = new int[3];
double[] mark = new double[3];
Map<Integer, Student> students = new HashMap<Integer, Student>();
students.put(s1.getID(), s1);
students.put(s2.getID(), s2);
students.put(s3.getID(), s3);
int i=0, index = 0;
for (Map.Entry<Integer, Student> entry: students.entrySet())
{
index = i++;
studentID[index] = entry.getKey();
mark[index] = entry.getValue().getMark();
}
for (int num=0; num<mark.length; num++)
{
System.out.println("ID: " +studentID[num]);
System.out.println("Mark: " +mark[num]);
}
}
}
My confusion lies in understanding the API. The getKey() returns K object. This K refers to Integer and V to Student assuming if I'm right.
1) Does this mean that I need to cast this line?
studentID[index] = entry.getKey();
to->
studentID[index] = (Integer)entry.getKey().intValue();
2)As the Value is a Student object. If I were to retrieve any of student variables, eg mark, I don't need to type cast it? ie double mark when entered into HashMap isn't converted to Double(obj). It still remains a double(prim). Is my understanding correct?
Thanks.