Java在TreeMap上迭代 - 不兼容的类型

gaz*_*lo4 3 java iteration iterator treemap

我有以下集合:

private Map <String, Staff> staff;
Run Code Online (Sandbox Code Playgroud)

实现为TreeMap:

staff = new TreeMap <String, Staff> ();
Run Code Online (Sandbox Code Playgroud)

我需要迭代这个映射中的值,但是当我尝试下面的代码时,我得到了一个不兼容的类型编译错误.我不明白为什么会这样; 我的地图中的值是Staff对象和

it.HasNext() 
Run Code Online (Sandbox Code Playgroud)

应该将它们返回存储在staffMember变量中,这应该对我的知识很好?非常感谢.

Collection <Staff> staffList = staff.values(); 
         Iterator it = staffList.iterator ();
         while ((isJobAssigned = false) ||it.hasNext())
         {
             Staff staffMember = it.next(); 
             if ((staffMember instanceof Typist) && (jobType.equalsIgnoreCase("Typist")))
             {
                 newJob.setJobState ("Assigned");
                 staffMember.setState("Working");
                 return newJon.getJobNo() + " Staff allocated: " + staffMember.getName () + ", ID: " + staffMember.getId();
                }
Run Code Online (Sandbox Code Playgroud)

Ale*_* C. 6

你正在使用原始的Iterator.要么你需要转换到StaffObject返回的it.next()或使用一个通用的Iterator.

使用原始迭代器:

Staff staffMember = (Staff)it.next(); 
Run Code Online (Sandbox Code Playgroud)

使用通用迭代器(我推荐这个版本):

Iterator<Staff> it = staffList.iterator();
Staff staffMember = it.next();  //you can keep this
Run Code Online (Sandbox Code Playgroud)

  • 如果可以指定类型,请不要使用原始迭代器,类型安全.+1 (2认同)