我必须创建一个arraylist的hashmap,但是arraylist可以是StudentRecord或TeacherRecord类型(它们是两个不同的类)我添加了两个记录但是我无法使用display method.can迭代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);
}
}
}
}
答案 0 :(得分:0)
一个简单的解决方案是覆盖每个类的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);
}
答案 1 :(得分:0)
让两个类都实现一个通用接口,例如
public interface PersonRecord {
String firstName();
String lastName();
...
}
和
public class StudentRecord implements PersonRecord
{ ... }
允许
List<PersonRecord> students = new List<>();
students.add(new StudentRecord());