User-defined class objects 在 Java TreeMap 中

User-defined class objects in Java TreeMap

我有一个 collection (TreeMap),我只想打印来自 Object 即时消息传递的一个值。这是我一直在尝试的代码

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);
        }
    }
}
  1. 我只想打印一个值,即 rollno 或 name 或 age

  2. 我还想将姓名打印为 Vijay,这只是来自 collection

请让我知道我正在尝试获取代码的错误的解决方案。

一张地图的entrySet是一组Map.Entry<KeyType, ValueType>

你有这个:

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();