gpt4 book ai didi

java hashmap无法转换对象

转载 作者:行者123 更新时间:2023-12-01 09:38:36 25 4
gpt4 key购买 nike

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更改为此。使用真正的 IDE(例如 Eclipse),它会自动发现此类错误并推荐解决方案(大多数情况下,这是有效的)。

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

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

关于java hashmap无法转换对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38625684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com