-1

Say, I have a class Alpha with two formal parameters K and V.

Now, I want to initialize an object of it with concrete types CK and CV.

I want to know, what's the difference between

Alpha<CK, CV> alpha = new Alpha<CK, CV>();

and,

Alpha<CK, CV> alpha = new Alpha();

Since, both won't allow me to write or read anything other than what they are declared as. And, since, generics is only for ensuring type safety during compile time, why does it throws warning if I can't do anything wrong with it?

Pkeakh Joqo
  • 141
  • 1
  • 4

1 Answers1

1

The issue with

Alpha<CK, CV> alpha = new Alpha();

is that on the left hand side, you are using the generic type Alpha where on the right side you are using the raw type Alpha. Raw types in Java effectively only exist for compatibility with pre-generics code and should never be used in new code unless you absolutely have to.

As far as your original example of Alpha<CK, CV> alpha = new Alpha(), the compiler generates a warning for that assignment because it must. Consider this:

List<String> strings = ... // some list that contains some strings

// Totally legal since you used the raw type and lost all type checking!
List<Integer> integers = new LinkedList(strings);

Generics exist to provide compile-time protection against doing the wrong thing. In the above example, using the raw type means you don't get this protection and will get an error at runtime. This is why you should not use raw types.

// Not legal since the right side is actually generic!
List<Integer> integers = new LinkedList<>(strings);
Olivier Poulin
  • 1,778
  • 8
  • 15