user3263853
user3263853

Reputation: 21

Passing a Hash Map to a Function - Java

Code:

public void saveFile(HashMap hashTable) {

    for (Employee e : hashTable.values()) {
            //...
    }
}

When I try to run this code, I receive the following error:

 incompatible types: Object cannot be converted to Employee 
           for (Employee e : hashTable.values()) {

Any assistance would be appreciated.

Upvotes: 2

Views: 6904

Answers (2)

rgettman
rgettman

Reputation: 178253

You used the raw form of HashMap, so hashTable.values() returns a raw Collection, which returns Objects, which can't be assigned directly to an Employee variable.

Use the generic form of HashMap, either:

public void saveFile(HashMap<?, Employee> hashTable) {

or

public void saveFile(HashMap<YourKey, Employee> hashTable) {

Then values() will return a Collection<Employee>, out of which you can extract Employees.

Or you might even use the Map interface, coding to the interface:

public void saveFile(Map<YourKey, Employee> hashTable) {

Upvotes: 1

Eran
Eran

Reputation: 393771

If the value of the map should be Employee, change the signature to :

public void saveFile(Map<TheKeyType,Employee> hashTable) {

where TheKeyType should be replaced with the type of your key (which is likely to be String or Integer).

when you use the raw Map type, hashTable.values() will return a raw Collection, so iterating over it will give you Object references, not Employee references.

Upvotes: 0

Related Questions