Rory Lester
Rory Lester

Reputation: 2918

Map inside a Map java

i'm new to java. I'm trying to pass parameters where a map is inside another map however i get an error "identifier expected"(found int, required reference).

This is the code :

package learning;
import java.util.*;
import java.text.SimpleDateFormat; 

    public interface Policy {

        public void toggleApp(Map<Map<Appliance,SimpleDateFormat>,int>toggle); *error here*

    }

     class Appliance
    {
       String appName = ""; 
       int appID; 
       double demand = 0.0;

    } 

Upvotes: 0

Views: 307

Answers (5)

Marcelo
Marcelo

Reputation: 4608

You can't have an int (primary type) in a Map, it only accepts Objects:

Map<Map<Appliance,SimpleDateFormat>, Integer > toggle;

Upvotes: 0

aioobe
aioobe

Reputation: 420991

You can't provide primitive types (such as int) as type parameters for generic classes.

Change

Map<Map<Appliance,SimpleDateFormat>,int>
                                    ^^^

to

Map<Map<Appliance,SimpleDateFormat>,Integer>
                                    ^^^^^^^

Also note that the first type argument is the type of the key and the second type parameter is the type of the values. My gut feeling is that you may have swapped them in your code.

Further reading:

Upvotes: 4

Johannes Weiss
Johannes Weiss

Reputation: 54031

The problem is the int as the value type of the map! int is a primitive and Java Generics only work for reference types.

Replace the int with Integer and it will work :-).

Since Java has auto boxing/unboxing, you can use the ordinary operations and it will automatically transform ints to Integers for you. map.put(key, 1) will work. It will do Integer.intValue(1) which is an Integer.

Upvotes: 2

soulcheck
soulcheck

Reputation: 36767

Change int to Integer.

Generics can only accept reference types as parameters.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

You cannot parametrise a generic (like Map<K,V>) on a primitive type (like int). Try using a wrapper class like Integer instead:

Map<Map<Appliance,SimpleDateFormat>,Integer>

Upvotes: 1

Related Questions