列表vs vs列表< Object> [英] List vs List<Object>
问题描述
为什么我们在使用 List
而不是使用 List< Object>
时失去了安全性?是不是他们基本上是同一件事?
编辑:我发现以下给出编译错误
public class TestClass
{
static void func(List< Object> o,Object s){
o.add或多个);
}
public static void main(String [] args){
func(new ArrayList< String>(),new Integer(1));
而这不是
public class TestClass
?是不是他们基本上是一样的东西?
{
static void func(List o,Object s){
o.add(s );
}
public static void main(String [] args){
func(new ArrayList< String>(),new Integer(1));
$ / code $ / pre
为什么?
<为什么我们在使用List
时丢失了类型安全性,而不是在使用code>列表与LT;对象>
不,它们不是一回事。
如果您正在提供API,那么
class API {
static List< Object> getList(){...}
static void modifyList(List< Object> l){...}
}
以及客户端使用不当
List< Integer> list = API.getList();
API.modifyList(list);
for(Integer i:list){...} //无效
然后当你的API指定了
List< Object>
它们得到一个编译时错误,但是当它们不是API.getList()
返回一个List
和API.modifyList(list)
需要一个List
没有泛型类型参数。
编辑:
void func(List< Object> s,Object c){s.add(c); }
到
void func(List s,Object c){s.add(c); }
这样
func(新列表< String>(),);
会起作用。
违反类型安全。这样做的类型安全的方式是:
< T> void func(List<?super T> s,T c){s.add(c); }
这基本上是说
func
是一个参数化函数,它接受一个List
,它的类型可以是T的任何超类,T类型的值,并将该值添加到列表中。Why do we lose type safety when using
List
and not while usingList<Object>
? Aren't they basically the same thing?EDIT: I found that the following gives a compilation error
public class TestClass { static void func(List<Object> o, Object s){ o.add(s); } public static void main(String[] args){ func(new ArrayList<String>(), new Integer(1)); } }
whereas this doesn't
public class TestClass { static void func(List o, Object s){ o.add(s); } public static void main(String[] args){ func(new ArrayList<String>(), new Integer(1)); } }
Why?
解决方案Why do we lose type safety when using
List
and not while usingList<Object>
? Aren't they basically the same thing?No they are not the same thing.
If you are providing an API,
class API { static List<Object> getList() { ... } static void modifyList(List<Object> l) { ... } }
and a client uses it improperly
List<Integer> list = API.getList(); API.modifyList(list); for (Integer i : list) { ... } // Invalid
then when your API specifies
List<Object>
they get a compile-time error, but they don't whenAPI.getList()
returns aList
andAPI.modifyList(list)
takes aList
without generic type parameters.EDIT:
In comments you mentioned changing
void func(List<Object> s, Object c) { s.add(c); }
to
void func(List s, Object c) { s.add(c); }
so that
func(new List<String>(), "");
would work.
That is violating type safety. The type-safe way to do this is
<T> void func(List<? super T> s, T c) { s.add(c); }
which is basically saying that
func
is a parameterized function that takes aList
whose type can be any super class of T, and a value of type T, and adds the value to the list.这篇关于列表vs vs列表< Object>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!