What are Raw Types?

Asked

Viewed 994 times

14

Reading and studying a little about Kotlin, I found the following statement:

The Raw Types are a big problem, but for reasons of compatibilities they had to be maintained in Java, but Kotlin for being a new language no longer has this problem.

What exactly are the Raw Types? And because they’re a big problem?

  • Oracle documentation A raw type is the name of a generic class or interface without any kind of argument.

  • 4

    Who denied the question could at least explain the reason why I can edit it and try to collaborate more with our community!

1 answer

16


What exactly are Raw Types?

According to the language specification, in free translation:

More precisely, a crude type is defined as being one of the following:

  • The type of reference that is formed taking the name of a declaration of generic type without a follow-up type argument list.

  • A matrix type whose element type is a crude type.

  • A non-static member type of a gross type R that is not inherited from a superclass or superinterface of R.

The term Raw Types became known with the introduction of Generics.

To illustrate, I will use the Framework Collections:

When Collections was designed in version 1.2 of Java, a collection did not specify what type of object it would handle, i.e., the collection could receive any type, as in the example:

List lista = new ArrayList();
lista.add(1);
lista.add("teste");

Manipulating an unbalanced collection as it is is costly, because when you take an element from the collection, you should assign it to its respective type, besides being inconvenient, it is not safe. The fact of not informing a type/argument to List is known as a Raw Type, or in free translation, a raw type.

Solving the Raw Type:

To solve this problem, in Java version 1.5, Generics, with this, it was possible to inform a type of the collection, as the example:

List<String> lista = new ArrayList<String>();
lista.add("teste_0");
lista.add("teste_1");

So once the compiler knows the type of element in the collection, the compiler can check if you have used the collection consistently and can enter the correct templates on the values being taken from the collection.

And because they’re a big problem?

In fact, Raw Types are a big problem, because even with the introduction of Generics it would not be convenient to remove Raw Types, as legacy applications need to continue running.

  • 3

    The only detail I notice is that while Java 5 and 6 require List<String> lista = new ArrayList<String>(); not to give a Warning of type rawtypes, from Java 7 can be used List<String> lista = new ArrayList<>();.

  • 1

    @Victorstafusa , diamond operator is beautiful and joy, avoids much repetition of the type name

Browser other questions tagged

You are not signed in. Login or sign up in order to post.