我有一个集合(TreeMap),我想从Object im传递中只打印一个值。这是我正在尝试的代码
Student.java
class Student {
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
public String toString(){//overriding the toString() method
return rollno+" "+name+" "+age;
}
}
StudentTest.java
import java.util.*;
import java.io.*;
class StudentTest{
public static void main(String args[]){
Map<String,Student> al=new TreeMap<String,Student>();
al.put("a1",new Student(101,"Vijay",23));
al.put("a2",new Student(106,"Ajay",27));
al.put("a3",new Student(105,"Jai",21));
Set set = al.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println(al.get("a1"));
System.out.println(al.size());
Set<String> keys =al.keySet();
for(String key : keys)
{
System.out.println(al.get(key));
}
Collection entrySet = al.entrySet();
Iterator<Student> itr = entrySet.iterator();
System.out.println("+++++++"+entrySet);
System.out.println("\n\n\n\n\n");
System.out.println("+++++++"+itr);
System.out.println("\n\n\n\n\n");
while(itr.hasNext())
{
Student st = itr.next();
System.out.println(st.rollno);
}
}
}
我想只打印一个rollno或name或age的值
此外,我想将名称打印为Vijay,它只是一个名字 集合
请让我知道我正在尝试的代码获取错误的解决方案。
答案 0 :(得分:1)
地图的entrySet
是一组Map.Entry<KeyType, ValueType>
s。
你有这个:
Collection entrySet = al.entrySet();
Iterator<Student> itr = entrySet.iterator();
如果您在第一行中没有使用原始类型,则错误将更加明显。永远不要使用原始类型:
Collection<Student> entrySet = al.entrySet(); // ERROR HERE - Set<Map.Entry<String, Student>> cannot be cast to Collection<Student>
Iterator<Student> itr = entrySet.iterator();
如果要迭代地图中的值,请使用values
:
Collection<Student> entrySet = al.values();
Iterator<Student> itr = entrySet.iterator();