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!
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.
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 ).
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With