user1604294
user1604294

Reputation:

How to use generics in parameter properly

I have this right now:

  public <T> void run(T x){

    if(x instanceof HashMap){
      ((HashMap<String,String>)x).put("foo","bar");
    }

  }

but I see this warning:

enter image description here

I have three questions:

  1. Does anyone know what that warning is about?
  2. Am I using the instanceof operator right? Is there a better/more accurate check to use?
  3. Is there some way of using generics so that the method "knows" what the type is so I don't have to cast the type?

Upvotes: 0

Views: 61

Answers (2)

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

This T can be of any type that extends Object and your code is not type safe. If anything otherthan HashMap<String, String> is passed in you may get a ClassCastException. But the use of instance of operator will prevent that from happening. But still anyone can send any object to your method. So the unchecked warning merely states that.

Use of instance of seems bit awkward to me here. Rather if you want to add an entry to existing map, you can change the declaration of your generic method like so,

public <S, T extends Map<S, S>> void addEntryToMap(T x, S key, S value) {
    x.put(key, value);
}

This code is type-safe, more cleaner and elegant than instance of check approach above.

Upvotes: 1

Mohamed Anees A
Mohamed Anees A

Reputation: 4591

I am not sure what are you trying to achieve in your method

public <T> void run(T x){ // Gets an unbounded T which means it can accept anything under Object.

    if(x instanceof HashMap){
      ((HashMap<String,String>)x).put("foo","bar"); // How are you so sure it is an HashMap<String,String>? It can be any HashMap,or even Object!! That is exactly why your compiler is telling it is doing an unchecked cast.
    }
  }

That answers your first point.

Second point, we need more clarity on this to explain.

Third point, There is something called type-erasure in Java where the generic method wont be able to know the type of object at runtime. You can pass in the class for casting or need to use bounded wild-cards for compile-time check.

Upvotes: 0

Related Questions