Rahul kishan Rahul kishan - 4 months ago 10
Java Question

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

}
}

Answer

Change your Map.Entry to this. Use a real IDE like Eclipse, it'll pick up such errors automatically and recommend solutions (which, most of the time, work).

From the perspective of Java Generics, it's a question of parametrising the Entry. The way it is declared there, it isn't parametrised. Either it ought be casted to Bikede or parametrised. Since generics are safer and avoid ClassCastException, I chose that solution.

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