1

In the example below, I can't seem to get rid of the unchecked warning (short of suppressing it). As you can see in '2.' specifying the type causes a compile error.

Is suppression the only option here?

static class Cat { }

static class CatGiver<T extends Cat> {

    T cat;

    CatGiver(T cat) {
        this.cat = cat;
    }

    static <T extends Cat> CatGiver<T> get() {
        // 1. Unchecked assignment warning
        return new CatGiver(new Cat());

        // 2. Compile error on 'new Cat()' "T cannot be applied to Cat..."
        // return new CatGiver<T>(new Cat());
    }
}
Michael
  • 41,989
  • 11
  • 82
  • 128
Andy Cribbens
  • 1,370
  • 2
  • 11
  • 22
  • Is your goal to create an instance of `T` inside the method? If so, then the answer is "you can't, without additional work (such as passing a `Class` in from the outside). See the answer I linked above. – Joachim Sauer Sep 04 '19 at 13:46
  • Think about when you create an ArrayList, you say `List list = new ArrayList<>();` so your first warning, you need to say `new CatGiver( new Cat());` and specify the type. – matt Sep 04 '19 at 13:51
  • @matt that causes a compile error "Incompatible types, Required CatGiver but found CatGiver" – Andy Cribbens Sep 04 '19 at 13:54
  • Right, because you method has a Generic parameter, that cannot be used. I have added an answer, if you actually need your class to have a `static ` then you should have your `get` take an argument. – matt Sep 04 '19 at 13:58
  • `return new CatGiver<>(new Cat())` and remove the generic type parameter from `get` – Michael Sep 04 '19 at 13:58
  • @Michael: that doesn't actually solve anything because `Cat` is not guaranteed to be assignable to `T`. – Joachim Sauer Sep 04 '19 at 14:01
  • @Michael Have you tried to compile code with solution from your comment? – Pshemo Sep 04 '19 at 14:01
  • 1
    What is the purpose of having generic type `` in `static CatGiver get() {` if you always `return new CatGiver(new Cat());`? What are you trying to accomplish here? – Pshemo Sep 04 '19 at 14:18
  • I think you are right. I was trying to achieve the ability to create other types later on that extend Cat. However, as that is not there yet, this example doesn't make too much sense. – Andy Cribbens Sep 04 '19 at 14:19

1 Answers1

2

First you're creating a raw type. You need to specify the type. Second, your static method, the 'T' is not variable and you can only return a Cat.

static CatGiver<Cat> get() {

    return new CatGiver<Cat>(new Cat());

}

You could have your cat be a generic type by passing an instance of a cat or the Class as the answers in the duplicate question.

static <T extends Cat> CatGiver<T> get(T cat){
    return new CatGiver<>(cat);
}

Then the T should be acquired implicitly from the argument. (I haven't tested.)

matt
  • 10,892
  • 3
  • 22
  • 34