Binyomin
Binyomin

Reputation: 367

How to pass an entire map

got another issue.

Im trying to send an entire Map of objects and their associated keys so that it can be accessed from another class. The method I am using does not work, as I tried to use the same method that is used to pass an array list, but it does not work for a Map.

what would be the correct way of doing it?

this is what I have tried

public Map <Integer, Employee> getAllEmps()
{ 
     return (Map <Integer, Employee>) ;
}

and this is how I have declared it (the actual map itself)

private static  Map <Integer, Employee> employeeMap = new TreeMap<Integer,Employee>();    

Upvotes: 0

Views: 241

Answers (4)

Maurice Perry
Maurice Perry

Reputation: 32831

You can return the variable itself:

public Map <Integer, Employee> getAllEmps()
{ 
     return employeeMap;
}

Which would allow anyone to modify the contnent of the map.

To prevent modification, you can return an unmodifiableMap:

public Map <Integer, Employee> getAllEmps()
{ 
     return Collections.unmodifiableMap(employeeMap);
}

Alternatively, you can return a copy:

public Map <Integer, Employee> getAllEmps()
{ 
     return new TreeMap<Integer,Employee>(employeeMap);
}

Upvotes: 2

Efthymis
Efthymis

Reputation: 1326

Why don't you try passing the variable itself and have the map as a member variable?

private Map <Integer, Employee> employeeMap = new Map <Integer, Employee>();    
public Map <Integer, Employee> getAllEmps()
{ 
     return employeeMap;
}

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160321

Your getAllMaps () function needs to actually return a map; do you mean it to return the static employeeMap?

Upvotes: 0

Tom
Tom

Reputation: 45174

You have to return the map instance, not the type.

public Class SomeClass{
     private static Map<Integer,Employee> employeeMap=...;

    //Other methods 


   public Map <Integer, Employee> getAllEmps()
  { 
      return employeeMap ;
  }
}

If you want only the employees (with no keys) you can add another method

 public Collection<Employee> getEmployees(){

     return employeeMap.values();
  }

Upvotes: 2

Related Questions