HashMap with multiple values under the same key

前端 未结 22 1882
旧时难觅i
旧时难觅i 2020-11-22 06:49

Is it possible for us to implement a HashMap with one key and two values. Just as HashMap?

Please do help me, also by telling (if there is no way) any other way to

22条回答
  •  死守一世寂寞
    2020-11-22 06:59

    I use Map for associating multiple values with a key in a Map. This way, I can store multiple values of different types associated with a key. You have to take care by maintaining proper order of inserting and retrieving from Object[].

    Example: Consider, we want to store Student information. Key is id, while we would like to store name, address and email associated to the student.

           //To make entry into Map
            Map studenMap = new HashMap();
            String[] studentInformationArray = new String[]{"name", "address", "email"};
            int studenId = 1;
            studenMap.put(studenId, studentInformationArray);
    
            //To retrieve values from Map
            String name = studenMap.get(studenId)[1];
            String address = studenMap.get(studenId)[2];
            String email = studenMap.get(studenId)[3];
    

提交回复
热议问题