9

In my interface:

public <T> Result query(T query)

In my 1st subclass:

public <HashMap> Result query(HashMap queryMap)

In my 2nd subclass:

public <String> Result query(String queryStr)

1st subclass has no compilation warning at all while 2nd subclass has: The type parameter String is hiding the type String? I understand my parameter is hidden by the generics type. But I want to understand underneath what exactly happened?

Shengjie
  • 12,336
  • 29
  • 98
  • 139

1 Answers1

17

It thinks you're trying to create a type parameter -- a variable -- whose name is String. I suspect your first subclass simply doesn't import java.util.HashMap.

In any event, if T is a type parameter of your interface -- which it probably should be -- then you shouldn't be including the <String> in the subclasses at all. It should just be

public interface Interface<T> {
  public Result query(T query);
}

public class Subclass implements Interface<String> {
  ...
  public Result query(String queryStr) { 
    ...
  }
}
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • 1
    As a style issue, I'd recommend against naming a type parameter `String` - or other commonly used Java class names. It will potentially confusing for anyone examining the code later on. If I see `String` in Java, I assume it's `java.lang.String`. – oconnor0 Apr 16 '12 at 17:04
  • 1
    Oh, absolutely. I suspect that the example I give here is what the OP _meant_ to do, though. – Louis Wasserman Apr 16 '12 at 17:08
  • You may also want to take a look at [this S&O question](http://stackoverflow.com/questions/10011758/troubleshooting-the-type-parameter-t-is-hiding-the-type-t-warning). – Go Dan Apr 16 '12 at 17:37
  • Yeah, I perhaps should have commented on the question instead of on your answer. :-) – oconnor0 Apr 16 '12 at 18:31
  • What I am trying to achieve here is that, it's up to the subclass to decide whether they want to pass java.lang.String or java.util.HashMap as parameter to query() method. Interface just needs to say, subclasses have to implement query method, but I don't care about what type of parameter subclasses want to pass in. @oconnor0 Is your answer here best practice for this? or I should just use a wild card in the interface like query(?) – Shengjie Apr 17 '12 at 09:26
  • @Shengjie, I think the code sample I gave above matches that use case as well as it's going to get. The subclass decides what type the query should have. – Louis Wasserman Apr 17 '12 at 14:56