user20150316
user20150316

Reputation: 101

TreeMap with generic key types

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

Answers (3)

Harald
Harald

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

Idos
Idos

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 ReferenceType

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (§15.16) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

Upvotes: 0

Henning Luther
Henning Luther

Reputation: 2075

The super type of both is Number so you can use this

Upvotes: 1

Related Questions