Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't add (int, double) pair to HashMap<Integer, Double>

Tags:

java

types

I'm working on a Java project right now, and I have a class I've created called DistanceQueue. It's signature is given by

public class DistanceQueue<Integer> extends PriorityQueue<Integer>

In this class, there is a method

public boolean add(int v)

which adds the key-value pair (v, Double.MAX_VALUE) to a HashMap called distances that is in the class DistanceQueue. However, inside of add(int v), when I type

distances.put(v, Double.MAX_VALUE);

I get the following error:

DistanceQueue.java:98: error: no suitable method found for put(int,double)
            distances.put(v, Double.MAX_VALUE);
                     ^
    method HashMap.put(Integer,Double) is not applicable
      (actual argument int cannot be converted to Integer by method invocation conversion)
  where Integer is a type-variable:
    Integer extends Object declared in class ShortestPaths.DistanceQueue
1 error

Does anyone know why I am getting this error? I thought Java automatically converted between int and Integer for you. Is there an easy way that I can fix it?

Thanks!

like image 220
Ryan Avatar asked Dec 08 '14 13:12

Ryan


People also ask

Can a HashMap store doubles?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

Can you put int in HashMap Java?

In the ArrayList chapter, you learned that Arrays store items as an ordered collection, and you have to access them with an index number ( int type). A HashMap however, store items in "key/value" pairs, and you can access them by an index of another type (e.g. a String ).

Can HashMap store integer?

Let's see a simple example of HashMap to store key and value pair. In this example, we are storing Integer as the key and String as the value, so we are using HashMap<Integer,String> as the type. The put() method inserts the elements in the map.

Can we use integer as key in HashMap?

It can store different types: Integer keys and String values or same types: Integer keys and Integer values. HashMap is similar to HashTable, but it is unsynchronized. It is allowed to store null keys as well, but there can only be one null key and there can be any number of null values.


1 Answers

You're using Integer as the name of a type parameter, which hides the java.lang.Integer.

public class DistanceQueue<Integer> extends PriorityQueue<Integer>
                           ^^^^^^^

You should probably just drop the type parameter:

public class DistanceQueue extends PriorityQueue<Integer>
like image 153
aioobe Avatar answered Oct 22 '22 00:10

aioobe