I am using a TreeMap to add entries that are of type <Integer,Long>
. However, I may have cases where the entries will be of type <Long, Long>
and I would like to construct a TreeMap that can handle both cases. So far, I have
public class myClass {
public TreeMap<Integer, String> myClass(String fileToRead) {
....
TreeMap<Integer, String> map = new TreeMap<>();
map.put(Integer, String); //this is a for loop that iterates through input list
}
return map
}
How do I add a generic key K that can be Integer or Long?
Edit: I would like to include other types, such as BigInteger
Sounds like you may want something like
public class MyClass<T extends Number> {
public TreeMap<T, String> myClass(String fileToRead) {
...
}
BigInteger
too would fill the Number
bill.
But to avoid the complication with the generics, I would actually suggest to always use Long
as the key type or even BigInteger
, except you have strong requirements not to do so. Depending on the JVM you use (64bit) an Integer
object may not even use less space than a Long
object.