Reputation: 101
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
Upvotes: 1
Views: 1244
Reputation: 5133
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.
Upvotes: 0
Reputation: 15320
You can always check the ReferenceType
with the instanceof
operator and work accordingly:
if (obj instanceof Long) { ... }
if (obj instanceof Integer) { ... }
From the JLS:
RelationalExpression
instanceof
ReferenceTypeAt run time, the result of the
instanceof
operator is true if the value of theRelationalExpression
is notnull
and the reference could be cast (§15.16) to theReferenceType
without raising aClassCastException
. Otherwise the result isfalse
.
Upvotes: 0