本文介绍了为什么是List< String>不是List< Object&gt ;?的子类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解列表< String> 列表< Object> 的子类型。

I am trying to make sense of the fact that List<String> is not a subtype of List<Object>.

在有效的Java中,Josh Bloch指出虽然它看似违反直觉,但确实有意义。他说的原因是你可以把任何对象放在 List< Object> 中,但只能把String放在 List< String> 。我不确定这是如何证明String列表不是Object列表的子类型的原因。

In effective Java, Josh Bloch notes that although it may seem counter-intuitive,it does make sense. The reason he stated is that you can put any Object in List<Object>, but can only put String in List<String>. I am not sure how this justifies why the String list is not a subtype of Object list.

也许我对术语子类型感到困惑。我认为这意味着当S是T的子类型时,S的实例是T的实例。因此,对于 List< String> 是一个子类型 List< Object> ,Object必须是String的超类,从技术上讲它是。知道我的推理出错了吗?

Maybe I am confused by the term subtype. What I think it means is that when S is a subtype of T, an instance of S is an instance of T. Therefore, for List<String> to be a subtype of List<Object>, Object has to be a super class of String, which it technically is. Any idea where my reasoning went wrong?

推荐答案

List<String> s = new ArrayList<String>();
List<Object> o = s;
o.add(new Object());
String first = s.get(0);  // boom

这篇关于为什么是List&lt; String&gt;不是List&lt; Object&gt ;?的子类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 09:16