简体   繁体   中英

Hashmap with Arraylist as values Android

I am developing an android application and I am using a Hashmap to store some data the app works fine when I define the Arraylist this way

ArrayList<String> eventList = new ArrayList<>(); 

but the app crashes when I change it to:

ArrayList<String> eventList = hmap.get(date);

I need to know the reason why?. And here is the whole function in case you need to have a look

HashMap<Date, ArrayList<String>> hmap = new HashMap<>();
void eventMaker(String d, String ev)  {
     Date date = null;
     try {
            date = df.parse(d);
     } catch (ParseException e) {
            e.printStackTrace();
     }
     long epoch = date.getTime();
     Event event = new Event(Color.RED,epoch,ev);
     compactCalendar.addEvent(event);
     ArrayList<String> eventList = new ArrayList<>();
     eventList.add(ev);
     hmap.put(date,eventList);
 }

您需要将Hashmap的值强制转换为必需的type。

  ArrayList<String> eventList =(ArrayList<String>) hmap.get(date);

The problem was that I was trying to get a value of a key that does not exist, I solved it like this:

if(!hmap.containsKey(date)){
            ArrayList<String> eventList =new ArrayList<>();
            eventList.add(ev);
            hmap.put(date,eventList);
        }
        else{
            ArrayList<String> eventList = hmap.get(date);
            eventList.add(ev);
            hmap.put(date,eventList);
        } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM