Java lang string incompatible with java util map

java.lang.ClassCastException cannot be cast to java.util.Map$Entry

I have this problem I can’t solve : I’m getting some data from fire base database. Every thing works fins except when I reach the title column because the title column is a json tree and it have a key values rows so a new logic must be writen here. What I tried so far
Create an entry for it and save it in hash map inside my ConfigItem class that I created. I receive the data just fine, but I don’t know who to loop through it. When I reach the third line in the while loop, I got java.lang.ClassCastException: java.util.HashMap$EntrySet cannot be cast to java.util.Map$Entry What I’m missing here?

public class DataMappingConfig implements DataMappingStrategy < @Override public Object mapData(HashMapdata ) < Log.i("key set " , data.keySet().toString() + " key set ") ; HashMapmpair =null ; HashMap titlepairs = null ; for (String key : data.keySet()) < if (key.equals(KEY_TITLE)) < final Iterator iterator = data.entrySet().iterator(); while (iterator.hasNext())< mpair = new HashMap() ; Map.Entry pair = (Map.Entry) data.entrySet() ; HashMap> titleMap = (HashMap) pair.getValue(); titlepairs = new HashMap();; > > > ConfigItem conf = new ConfigItem(); if (data.containsKey(KEY_LOGIN)) < conf.setLogin((Boolean) data.get(KEY_LOGIN)); // note the import above >if (data.containsKey(KEY_ICON)) < conf.setIcon((String) data.get(KEY_ICON)); >if (data.containsKey(KEY_MAIN_SCREEN_ORDER)) < conf.setNum(safeLongToInt((Long) data.get(KEY_MAIN_SCREEN_ORDER))); >if (data.containsKey(KEY_MODE)) < String modeValue = (String) data.get(KEY_MODE); if (modeValue.equals(VALUE_MODE_EMERGENCY)) < conf.setEmenrgency(true); >else if (modeValue.equals(VALUE_MODE_ROUTINE)) < conf.setRoutine(true); >conf.setMode((String) data.get(KEY_MODE)); > if (data.containsKey(KEY_STATUS)) < conf.setStatus((String) data.get(KEY_STATUS)); >if (data.containsKey(KEY_SHOW_DATE)) < try < conf.setShowDate((Boolean) data.get(KEY_SHOW_DATE)); >catch (IllegalArgumentException e) < e.printStackTrace(); Log.i("ERROR", "" + e.getLocalizedMessage()); >> Log.i("Data Map config ", "conf item = " + conf.toString() + "\n"); return conf; > > 

@Wajdi: If your problem has been solved, add an answer and accept that. If you think the question is not useful anymore delete it. Either way: don’t remove the question body.

Источник

java.lang.String cannot be converted to java.util.HashMap

When I run my code I get a screen that asks for a reference(already coded and works perfectly). So when I input IW1 for reference my output should be the details of IW1 which is «IW1», new troop(1, «Twisters», 200, 200)) . However I get with the following error: Exception in thread «main» java.lang.RuntimeException: Uncompilable source code — incompatible types: java.lang.String cannot be converted to java.util.HashMap The OODCwk is the name of the package

public String getTroopDetails(String ref) < if ("IW1".equals(ref) )< HashMapTroop= getTroopDetails(ref); System.out.println(Troop.get("IW1")); >else < return "!"; >return "\nNo such troop"; > private void setupTroop() < HashMapTroop= new HashMap(); Troop.put("IW1", new troop(1, "Twisters", 200, 200)); > public class troop < int FleetRef; String FullName; int ActivationFee; int BattleStrength; public troop(int FRef, String FName, int AFee, int BStrength) < FleetRef = FRef; FullName = FName; ActivationFee = AFee; BattleStrength = BStrength; >public int getFleetRef() < return FleetRef; >public String getFullName() < return FullName; >public int getActivationFee() < return ActivationFee; >public int BattleStrength() < return BattleStrength; >> 

@paulsm4 Exception in thread «main» java.lang.RuntimeException: Uncompilable source code — Erroneous sym type: OODCwk.SpaceTroops.setupTroop this is the error i get if i do that. SpaceTroops is a class that has the method setupTroop

What for is recursive invocation getTroopDetails in the method getTroopDetails ? Method setupTroop declared as void but it returns the hashmap Troop .

Источник

HashMap ClassCastException

введите сюда описание изображения

Не понял, в чём проблема? Консоль:

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer 
private HashMap RanksList = new HashMap<>(); if (this.getConfig().contains("PlayerRank")) < this.RanksList = (HashMap) this.getConfig().getConfigurationSection("PlayerRank").getValues(false); >else

2 ответа 2

Предположим, что метод getValues возвращает Map :

private static Map getValues() < HashMapmap = new HashMap<>(); map.put("abc", "def"); return map; > 

Если некорректно с ним работать (с использованием raw-type вместо generics), то вполне возможна такая ситуация:

public static void main(String[] args) < HashMapranksList = (HashMap)getValues(); for (int i : ranksList.keySet()) < System.out.println("Key: " + i); >> 

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

Так как на самом деле в хэш-таблице в качестве ключей участвуют String , а сделать Integer из String простым приведением типа нельзя.

HashMap ranksList = (HashMap)getValues(); 

То была бы ошибка компиляции:

java.lang.RuntimeException: Uncompilable source code — incompatible types: java.util.Map cannot be converted to java.util.HashMap

Можно предположить, что метод getValues возвращает просто Map , из-за чего уже и

 HashMap ranksList = (HashMap)getValues(); 

не спасёт ситуацию (код скомпилируется, но ClassCastException , конечно, никуда не денется), но это уже будет вина разработчиков метода getValues .

И, судя по новому скриншоту

screenshot

Метод getValues возвращает Map , который содержит в качестве ключей String и который не стоит пытаться кастовать к Map , потому что ни тип ключей не совпадает, ни тип значений.

Если нельзя изменить возвращаемый getValues тип, то можно создать Map на базе Map :

HashMap ranksList = new HashMap<>(); Map map = getValues(); for (String key : map.keySet())

Или с использованием Java 8:

HashMap ranksList = new HashMap<>(); Map map = getValues(); map.forEach((key, value) -> ranksList.put(Integer.parseInt(key), String.valueOf(value))); 

Также не стоит забывать, что если какой-то из ключей в map не подходит под формат, принимаемый методом Integer.parseInt , то будет проброшено NumberFormatException .

Источник

Incompatible types error while using stream and collector with ArrayList of Maps

The caller resultList is an ArrayList, which is an array of JSON(s). I want to parse each element into map, filter the map, and collect the arrays of maps. The code in the above line has no complier error. But at runtime it gives error as:

Error:(51, 25) java: incompatible types: cannot infer type-variable(s) R,A,capture#1 of ?,T,C,E (argument mismatch; java.util.stream.Collector,capture#2 of ?,java.util.ArrayList> > cannot be converted to java.util.stream.Collector >) 

I’ve tried many different ways like Collectors.toList() but it doesn’t work. I’m still after a clean solution for parsing each String element to map and collecting all of them as an ArrayList. Update: the parser is from com.json.parsers.JSONParser;

1 Answer 1

According to the (almost cryptic) error message, the problem is in the parseJson method of your parser instance, which is returning a raw Map , i.e. a map that doesn’t specify the types of its keys and values.

You need that method to return a Map , or at least, to be generic, so that it can return the required type.

EDIT: I’ve never heard of your JSON parser. A quick google search showed that it is barely used and it seems like it’s an archived project. I highly recommend you to move to a better JSON library, such as Jackson, Gson or maybe JSON.simple.

A quick and dirty solution with what you already have would be to cast the returned map to Map , if you’re sure that you actually have strings as values for all your keys (otherwise you might face the dreaded ClassCastException ).

To accomplish this, you should change your code to:

List> resultArray = resultList.stream() .map(json -> (Map) parser.parseJson(json)) .filter(ev -> ev.entrySet().containsAll(filter.entrySet())) .collect(Collectors.toCollection(ArrayList::new)); 

But, again, bear in mind that this is not very clean and that you might be introducing more bugs with that cast. Best solution would be to use i.e. Jackson:

ObjectMapper mapper = new ObjectMapper(); // Jackson JSON lib entry-point List> resultArray = resultList.stream() .map(json -> < try < return mapper.readValue(json, new TypeReference>() <>); > catch (IOException e) < throw new UncheckedIOExpcetion(e); >>) .filter(ev -> ev.entrySet().containsAll(filter.entrySet())) .collect(Collectors.toCollection(ArrayList::new)); 

Recommendation: you’d better move the whole try/catch block inside the map operation to a private method that returns Map .

Источник

Java Collections — Maps and Sets: put cannot be applied

I’m having trouble with some code. I am trying to create a student database. I need to create a set of students that is represented by a course name. The course name is mapped to the set of students. I’ve tried to write the ‘add’ method but when I try to .put it into the database I get an error message: put(java.lang.String,java.util.Set) in java.util.Map> cannot be applied to (java.lang.Integer,StudentDatabase.Student). Any help is greatly appreciated. import java.util.*; public class StudentDatabase

private Map> database = new TreeMap>(); private static class Student extends TreeSet  < public int id; public Student(int id)< this.id = id; >> public void add(String courseName, Integer student) < /* I've tried to use this way to add to the database and it doesn't work too. SetstudentSet = database.get(courseName); if (studentSet == null)< studentSet = new TreeSet(); > studentSet.add(student); database.put(courseName, student); */ Integer idInt = new Integer(idInt); if (database.containsKey(idInt)) < //if the student is a duplicate, that is ok >else < Student info = new Student(idInt); database.put(new Integer(idInt), info); >> // end add 

I just built something almost exactly what you are doing. Add some comments explaining what your set is storing and what you are mapping and I can help. Is this a school project? If so, post a link to the assignment if available.

the set stores student id numbers. each course is represented as a set of student id numbers. the database must map from course names to id sets.

I think it is quite simple and I can help you out. But I couldn’t get what is idInt in your add method? Please provide some detail about it.

Источник

Читайте также:  hi!
Оцените статью