java hashmap 无法转换对象

java hashmap cannot convert object

In Hashmap I send a string and a my own class object as parameter i have sent that successfully but when i want that object it cannot be converted it shows the error

Main.java:37: error: incompatible types: Object cannot be converted to Bikede

Bikede obb= e.getValue();

import java.util.*;
import java.lang.*;
import java.io.*;

class Bikede
    {
        int bikeno;
        boolean vacancy;
        public Bikede(int a,boolean b)
        {
            bikeno=a;
            vacancy=b;
        }

    }
class Ideone
{

    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner obj=new Scanner(System.in);
        int n=obj.nextInt();

        HashMap<String,Bikede> lh=new HashMap<String,Bikede>();

        for(int i=0;i<n;i++)
        {
        int bno;
        boolean parked;
        bno=obj.nextInt();
        parked =true;
        lh.put(""+i,new Bikede(bno,parked));
        }
        for(Map.Entry e:lh.entrySet())
        {

            Bikede obb= e.getValue();
            System.out.println(obb.bikeno);
        }

    }
}

把你的Map.Entry改成这个。使用像 Eclipse 这样的真正的 IDE,它会自动拾取此类错误并推荐解决方案(大部分时间都有效)。

从Java泛型的角度来看,就是Entry参数化的问题。它在那里声明的方式没有参数化。它应该被转换为 Bikede 或参数化。由于仿制药更安全并且避免 ClassCastException,我选择了该解决方案。

for (Entry<String, Bikede> e : lh.entrySet()) {
    Bikede obb = e.getValue();
    System.out.println(obb.bikeno);
}