0

Consider this very simple generic class:

class GenericTest<T> {
    T t;
    GenericTest(T t) {
        this.t = t;
    }
}

I created multiple objects of this class, one of them is raw type:

class App {
    public static void main(String[] args) {
        GenericTest<String> test1 = new GenericTest<>("Test 1");
        GenericTest<String> test2 = new GenericTest<>("Test 2");
        GenericTest<String> test3 = new GenericTest<>("Test 3");

        GenericTest raw = new GenericTest(1.0); // Line 19

        test1 = raw; // Line 21
        test2 = raw; // Line 22
        raw = test3; // Line 23
    }
}

when compiling the project it shows 3 warnings for these lines:

App.java:19: warning: [unchecked] unchecked call to GenericTest(T) as a member of the raw type GenericTest
App.java:21: warning: [unchecked] unchecked conversion
App.java:22: warning: [unchecked] unchecked conversion

My question is why it doesn't give a warning for the third assignment raw = test3;?


One possible answer: because it does not cause any further loss of type safety that already had occurred.

  • but it also was true when the second assignment test2 = raw; (line 22) so it should not issued any warning for the same reason, because it does not cause any further loss of type safety than line 21.
Mehdi Rahimi
  • 1,453
  • 5
  • 20
  • 31
  • 1
    Java is statically typed, the type of `raw` doesn't change because of an assigment. So it still is `GenericTest` and not `GenericTest`. – M. Deinum Jul 12 '23 at 08:55
  • `raw` can hold all of them. `test1` and `test2` should crash after assigning them. There is no warning because no implicit unchecked casting happens – Shark Jul 12 '23 at 08:56

1 Answers1

2

Consult the language specification for the definition of Unchecked conversion:

There is an unchecked conversion from the raw class or interface type (§4.8) G to any parameterized type of the form G<T1,...,Tn>.

There is an unchecked conversion from the raw array type G[]k to any array type of the form G<T1,...,Tn>[]k. (The notation []k indicates an array type of k dimensions.)

Note that the direction of conversion is from raw to parameterized.

To answer the question as to why you don't need to be warned about a conversion in the parameterized to raw direction: yes, it's because "it does not cause any further loss of type safety that already had occurred", as you suggested in the question.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243