[FIXED] Generic type get method doesn't work in a foreach loop – java: incompatible types: java.lang.Object cannot be converted to Error

Issue

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

Solution

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

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

Answered By – VondeTaconadis

Answer Checked By – Katrina (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published