Home > front end >  Generic type get method doesn't work in a foreach loop - java: incompatible types: java.lang.Ob
Generic type get method doesn't work in a foreach loop - java: incompatible types: java.lang.Ob

Time:08-27

I am studying Generics in Java in Oracle docs. In Type Inference & Generic Methods section there is this code and it is not working in Intellij Idea.

This is Box class

package org.example;

public class Box<T> {
   
    private T t;

    public void set(T t) { this.t = t; }
    public T get() { return t; }
}

This is BoxDemo class.

package org.example;

import java.util.List;

public class BoxDemo {

    public static <U> void addBox(U u, List<Box<U>> boxes) {
        Box<U> box = new Box<>();
        box.set(u);
        boxes.add(box);
    }

    public static <U> void outputBoxes(List<Box<U>> boxes) {
        //No Error 
        U boxContents = boxes.get(0).get();

        for (Box box : boxes) {
            
            //**java: incompatible types: java.lang.Object cannot be converted to U**
            U boxContents2 = box.get();


            System.out.println(
                    boxContents2.toString());

        }

    }
}

Here is Screen

CodePudding user response:

Try to change your for and iterate from boxes the type Box box instead of Box box

for(Box<U> box : boxes){
      ....
}
  • Related