1

Дан код java

public class C {

    interface BT<T> {
        List<String> getList();
    }
    
    public static void method1(BT b) {
        for (String item : b.getList()) {}  // incompatible types: Object cannot be converted to String
    }

    public static void method2(BT b) {
        for (Object item : b.getList()) {}
    }
    
    public static void method3(BT<Integer> b) {
        for (String item : b.getList()) {}
    }
    
}

Почему в методе method1 возникает ошибка incompatible types: Object cannot be converted to String?
Ладно бы был BT<T> { List<T> getList() }. Но почему параметр T имеет такое влияние на метод, который с ним связан лишь тем, что просто оба прописаны в одном интерфейсе?

1 ответ 1

3

Это следствие использования сырого (raw) типа.

При использовании raw типов, как у вас BT в методе method1, все типы его методов и полей тоже становятся сырыми согласно спецификации:

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

1
  • Любопытно было бы узнать, почему принята такая спецификация?
    – Sergey
    4 фев 2022 в 0:15

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.