-
October 13th, 2014, 01:07 PM
#1
Casting one class object as anoter class object
Hi,
I am using java 8SE. I am trying to loop through a hashmap of objects(of class Person). There are subclasses of Person called Instructor and Student. As I loop through the map, I am trying to see if I have a match of class Instructor, and cast that Person object as Instructor, so that I may use its methods.
I keep getting the following runtime error:
java.lang.ClassCastException: java.util.HashMap$Node cannot be cast to uStaff.Instructor
at uStaff.PersonApp.menu(PersonApp.java:108)
at uStaff.PersonApp.main(PersonApp.java:21)
Here is a code snippet:
Code:
//Instantiate the different Person, student and instructor objects
Person thisPerson = new Person(01,fName,mName,lName,email,ssn,age);
Student thisStudent = new Student(02,"Stacey","Marie","Morgan","smorgan@gmail.com","213-45-6789",20);
thisStudent.setMajor("music");
Instructor thisInstructor = new Instructor(03,"Joe","Douglass","Wells","joe@drumhaven.com","555-98-3029",46);
thisInstructor.setDepartment("Computer Science");
//Create hashmap of the different objects
HashMap<Integer,Person> Ustaff = new HashMap<Integer,Person>();
Ustaff.put(01, thisPerson);
Ustaff.put(02, thisStudent);
Ustaff.put(03, thisInstructor);
for (Map.Entry<Integer, Person> entry : Ustaff.entrySet()){
System.out.println( entry.getValue().toString() + " " + " \n " + entry.getValue().getEmailDomain() + "\n " + entry.getValue().getLast4SSN() + "\n");
if (entry.getValue().getClass().getSimpleName().equals("Instructor"))
{
System.out.println(((Instructor)entry).getDepartment());
}
//+ ((Instructor) entry.getValue()).getDepartment() + " " + ((Student) entry.getValue()).getMajor());
if (entry.getValue().getAge() >= entry.getValue().getEldest()) {
System.out.println("Oldest\n");
}
else {
System.out.println("Not the oldest\n");
}
}
}
}
}
Im not quite sure what i am doing wrong.
-
October 16th, 2014, 06:52 PM
#2
Re: Casting one class object as anoter class object
The Map.Entry object contains the key and value. To get either, you need to call a get method that returns the object you want. See the API doc for a description.
Norm
-
October 17th, 2014, 07:59 AM
#3
Re: Casting one class object as anoter class object
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
|
Click Here to Expand Forum to Full Width
|