Skip to content

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

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<>();

    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();




Here is Screen



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

for(Box<U> box : boxes){
User contributions licensed under: CC BY-SA
9 People found this is helpful