Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics in for each loop problem if instance does not have generic type assigned [duplicate]

Tags:

java

generics

Could someone please explain to me why there is explicit need to assign generic type for ForEachLoop instance?

Why compiler complains: Type mismatch: cannot convert from element type Object to String?

JDK 1.5.0_09

import java.util.ArrayList;
import java.util.Collection;

public class ForEachLoop<T> {

public static void main(String[] args) {

    // Non functional version
    ForEachLoop f = new ForEachLoop(); 

    // Functional version
    //ForEachLoop<Integer> f = new ForEachLoop();

            // Type mismatch: cannot convert from element type Object to String
    for(String a : f.getStrings()) {
        System.out.println(a);
    }
}

public Collection<String> getStrings() {
    Collection<String> strings = new ArrayList<String>();
    strings.add("Hello");
    return strings;
}

} 
like image 760
Fekete Kamosh Avatar asked Jul 23 '10 07:07

Fekete Kamosh


People also ask

Which of the following statement is incorrect about generics?

Which of the following is an incorrect statement regarding the use of generics and parameterized types in Java? Explanation: None.

Why do we need generics explain with an example of how generics make a program more flexible?

Type check at compile time −usually, when you use types (regular objects), when you pass an incorrect object as a parameter, it will prompt an error at the run time. Whereas, when you use generics the error will be at the compile time which is easy to solve.

Why do we use generics for getting a list of multiple elements?

Code that uses generics has many benefits over non-generic code: Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

Which of these type Cannot be used to initiate a generic type?

1. Which of these types cannot be used to initiate a generic type? Explanation: None.


1 Answers

This is a rather common mistake:

ForEachLoop f = new ForEachLoop(); 

should be

ForEachLoop<Something> f = new ForEachLoop<Something>();

If you use the raw type (which you shouldn't) the compiler will erase all generic information for that instance even if it's not the type parameter T, to make it compatible with pre 1.5 code.

Only use raw types if you're writing for Java 1.4 or less, in which case you shouldn't have any generics whatsoever. At the bytecode level the method returns a Collection (raw) after type erasure. Normally, if the instance has the generic type set, when you try to do get on the collection, the compiler will use the generic information to decide that it should return a String, and then at the bytecode level it automatically casts the Object it receives from the Collection to String (since it's guaranteed to be a String). But if you use the raw type the compiler will ignore all generic information and will not automatically cast the object for you anymore.

Edit: In the section on Raw Types there are these things:

Another implication of the rules above is that a generic inner class of a raw type can itself only be used as a raw type:

class Outer<T>{
  class Inner<S> {
    S s;
  }
}

it is not possible to access Inner as partially raw type (a "rare" type)

Outer.Inner<Double> x = null; // illegal
Double d = x.s;

because Outer itself is raw, so are all its inner classes, including Inner, and so it is not possible to pass any type parameters to it.

The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.

It is a compile-time error to attempt to use a type member of a parameterized type as a raw type.

This means that the ban on "rare" types extends to the case where the qualifying type is parameterized, but we attempt to use the inner class as a raw type:

Outer<Integer>.Inner x = null; // illegal

This is the opposite of the case we discussed above. There is no practical justification for this half baked type. In legacy code, no type parameters are used. In non-legacy code, we should use the generic types correctly and pass all the required actual type parameters.

Notice that the Inner class has it's own type parameter independent of the one of the Outer class, and it still gets erased. Basically they don't want us mixing raw and generic types on the same instance, since it doesn't make sense in any version (in pre 1.5, the generic part will be an error, in 1.5+ the raw type is discouraged, and may even be removed from future versions)

Then there's also this:

The type of a constructor (§8.8), instance method (§8.8, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the erasure of its type in the generic declaration corresponding to C. The type of a static member of a raw type C is the same as its type in the generic declaration corresponding to C.

It is a compile-time error to pass actual type parameters to a non-static type member of a raw type that is not inherited from its superclasses or superinterfaces.

which says that constructors, instance methods and non-static fields will be treated as raw in a raw instance. Static members will be treated as generic anyway, since they don't require an instance to be accesed.

like image 119
Andrei Fierbinteanu Avatar answered Oct 16 '22 14:10

Andrei Fierbinteanu