-14

I have this code :

ArrayList<Integer> users = new ArrayList<Integer>();

Map <String,Object> hashMap = new HashMap <String,Object> ();

hashMap.put("users",user);

// now I want to get users as array list
 hashMap.get("users")[i];//error

How to users as array ? thank you

david
  • 157
  • 1
  • 1
  • 12

4 Answers4

3
List<Integer> users = new ArrayList<Integer>();

Map<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("users",user);
....
....
....
List<Integer> users = (List<Integer>)hashMap.get("users"); //assuming this is another method and 'users' is not defined here yet
Integer[] usersArray = users.toArray(new Integer[users.size()]);
System.out.println("" + usersArray[i]);

Please note that this is an atrocity and you shouldn't be storing that List as an Object, you are pretty much circumventing what Generics are for.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
2

This code will work if you want to access it as an ArrayList:

List<Integer> users = new ArrayList<Integer>();
Map<String, List<Integer>> hashMap = new HashMap<String, List<Integer>> ();
hashMap.put("users",users);
hashMap.get("users");

Your code won't work since you were storing it as an Object. So you would need a cast. And even then you use [] for arrays, not ArrayLists

If you want to use it as an array you can change the last line to:

hashMap.get("users").toArray()

And then you can use [1], or just do .get(1) on the initial code.

Alternatively, if you want to use hashMap as a property bag as someone validly mentioned you would need to do a cast:

((ArrayList<Integer>) hashMap.get("users"))

Then you can use users as an ArrayList as you are getting an Object by default from the HashMap.

Simon Verhoeven
  • 1,295
  • 11
  • 23
1

Because it is ArrayList and not array,You can get it like this-

public static void main(String args[]) throws Exception
{
  ArrayList<Integer> users = new ArrayList<Integer>();
  users.add(5);
  users.add(10);

  Map <String,Object> hashMap = new HashMap <String,Object> ();

  hashMap.put("users",users);

  ArrayList<Integer> no =  ((ArrayList<Integer>) hashMap.get("users"));

   for (Integer integer : no) {
    System.out.println(integer);
   }
}

output-

5
10

Now to convert ArrayList to Array -

Integer[] arr = no.toArray(new Integer[no.size()]);
Ninad Pingale
  • 6,801
  • 5
  • 32
  • 55
1

You can try something like following

List<Users> usersList = new ArrayList<>();
Map<String,List<Users>> hashMap = new HashMap <> ();
hashMap.put("user",usersList);

Now

hashMap.get("user")

Will return a List of Users, Now you can use

hashMap.get("user").get(0); // to get 0th index user
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115