Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Is casting from Iterable<?> to Iterable<Object> always safe?
Iterable<?>
Iterable<Object>
It looks like it is, since I can't see any way how to misuse it to produce a
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.
ClassCastException
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?
在 的情况下Iterable,是的,因为它没有任何采用 a 的T方法,只有返回 a 的方法T(嗯,通过它的迭代器)。编辑:见下文。
Iterable
T
Java 没有协变类与逆变类的正式概念,这就是为什么它无法区分 anIterable<T>和 a List<T>(后者从to 转换为不安全)的原因。由于它没有这种区别,它被迫警告你演员阵容可能不安全。毕竟,不安全并不意味着事情会破坏,它只是意味着编译器不能保证它们不会。List<?>List<Object>
Iterable<T>
List<T>
List<?>
List<Object>
编辑: maaartinus 找到了一个很好的反例。只有当 Iterable 是不可变的时,以上才是正确的;但当然,不可变类型通常无论如何都是协变的(即使 Java 不承认这一点,因为它不承认不可变性)。
现在我知道是什么困扰了我:
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!"); } }
所以演员是安全的,只要你不向上,不要让不安全的东西逃跑。