[英]Iterating hashmap of arraylist of two different Class types
我必须创建一个arraylist的哈希表,但是arraylist的类型可以是StudentRecord或TeacherRecord(这是两个不同的类),我添加了两个记录,但是我无法使用显示方法遍历hashmap的内容。有人可以帮助我吗?定义显示功能?
public class StudentRecord
{
String first_Name;
String last_Name;
String [] courses_Registered;
String status;
Date date;
StudentRecord(String f_name,String l_name,String [] courses,String status,Date dat )
{
this.first_Name=f_name;
this.last_Name=l_name;
this.courses_Registered=courses;
this.status=status;
this.date=dat;
}
}
public class TeacherRecord
{
String first_Name;
String last_Name;
String address;
String phone;
String specilization;
String location;
TeacherRecord(String f_name,String l_name,String addr,String number,String spec,String loc )
{
this.first_Name=f_name;
this.last_Name=l_name;
this.address=addr;
this.phone=number;
this.location=loc;
}
}
public class Montreal_server
{
String record_id;
ArrayList<StudentRecord> student_arraylist=new ArrayList<StudentRecord>();
ArrayList<TeacherRecord>teacher_arraylist=new ArrayList<TeacherRecord>();
HashMap<String,ArrayList> map=new HashMap<String,ArrayList>();
void createTRecord(String f_name,String l_name,String addr,String number,String spec,String loc)
{
TeacherRecord t=new TeacherRecord(f_name,l_name,addr,number,spec,loc);
teacher_arraylist.add(t);
map.put("x",teacher_arraylist);
}
void createSRecord(String f_name,String l_name,String [] courses,String status,Date dat)
{
StudentRecord s=new StudentRecord(f_name,l_name,courses,status,dat);
student_arraylist.add(s);
map.put("s",student_arraylist);
}
void display()
{
System.out.println("inside display");
for(Entry<String, ArrayList> en : map.entrySet())
{
java.util.Iterator<StudentRecord> itr = ((List<StudentRecord>)student_arraylist).iterator();
while(itr.hasNext())
{
Object c=(Object)itr.next();
System.out.println(c.first_Name+" "+c.last_Name+" "+c.status+" "+c.date+" "+c.courses_Registered);
}
}
}
}
一个简单的解决方案是在每个类上重写toString()
:
public class StudentRecord {
// fields, constructor etc.
@Override
public String toString() {
return first_Name+" "+last_Name+" "+status+" "+date+" "+Arrays.toString(courses_Registered);
}
}
为TeacherRecord
创建类似的方法。 现在,在循环中,只需调用System.out.println(c);
,这将隐式打印toString()
实现的结果。
此外,很多困惑是由于试图将包含无关类型的列表强制转换为单个映射而导致的。 最简单的解决方案是仅单独打印每个列表:
void display() {
student_arraylist.forEach(System.out::println);
teacher_arraylist.forEach(System.out::println);
}
让两个类都实现一个公共接口,例如
public interface PersonRecord {
String firstName();
String lastName();
...
}
和
public class StudentRecord implements PersonRecord
{ ... }
这使得
List<PersonRecord> students = new List<>();
students.add(new StudentRecord());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.