8

Is casting from Iterable<?> to Iterable<Object> always safe?

It looks like it is, since I can't see any way how to misuse it to produce an unexpected ClassCastException, but I guess I'm missing something.


I want to create a live updating score ticker using google docs and jQuery

Currently, on my website, I have static tickers where the data, from a google docs spreadsheet, will only get pulled in when the page is initially loaded. So I was hoping to make some sort of JS widget where, maybe based on a timed basis, news scores would get pulled in without the page being refreshed. Is this (jQuery-> Google Docs relationship) possible? and if so how could I do this?

4

2 回答 2

6

在 的情况下Iterable,是的,因为它没有任何采用 a 的T方法,只有返回 a 的方法T(嗯,通过它的迭代器)。编辑:见下文。

Java 没有协变类与逆变类的正式概念,这就是为什么它无法区分 anIterable<T>和 a List<T>(后者从to 转换为不安全)的原因。由于它没有这种区别,它被迫警告你演员阵容可能不安全。毕竟,不安全并不意味着事情破坏,它只是意味着编译器不能保证它们不会List<?>List<Object>

编辑: maaartinus 找到了一个很好的反例。只有当 Iterable 是不可变的时,以上才是正确的;但当然,不可变类型通常无论如何都是协变的(即使 Java 不承认这一点,因为它不承认不可变性)。

于 2013-10-17T18:17:52.700 回答
4

现在我知道是什么困扰了我:

Integer blown() {
    List<Integer> intList = new ArrayList<Integer>();
    Iterable<?> iterable = intList;

    @SuppressWarnings("unchecked") // This cast should be safe, shouldn't it?
    Iterable<Object> objectIterable = (Iterable<Object>) iterable;
    safeMethod(objectIterable);

    return intList.get(0);
}

// This method is definitely fine, no unchecked cast.
private void safeMethod(Iterable<Object> objectIterable) {
    if (objectIterable instanceof List) {
        List<Object> list = (List<Object>) objectIterable;
        list.add("blown!");
    }
}

所以演员是安全的,只要你不向上,不要让不安全的东西逃跑。

于 2013-10-17T18:37:39.690 回答