Java参考分配与通用列表 [英] Java Reference assignment with generic lists

查看:136
本文介绍了Java参考分配与通用列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得很蠢,要求我这样。

I feel stupid asking this but I am.

List< HasId> ids = list 在下面的代码中给出一个编译错误:

The line List<HasId> ids = list is giving a compile error in the following code:

public class MyGarbageClass {

    public void myMethod(List<MyCompany> list){
        List<HasId> ids = list;
    }

    interface HasId {
        int getId();
    }
    class MyCompany implements HasId{
        private int id = 5;
        @Override
        public int getId() {
            return id;
        }
    }
}

MyCompany实现HasId我应该能够分配它。为什么不能我? 更重要的是,将一个简单的方法分配给HasId对象列表。

MyCompany implements HasId so I thought I should be able to assign it. Why cant I? And more importantly, what is an easy way to assign this to HasId list of objects.

更新:列表

推荐答案

不允许这样的泛型赋值的原因是可以做转换,然后添加一些到 ids 这不是一个MyCompany(也许MyPerson也实现HasId )。

The reason why generic assignment like this is disallowed is it possible to do the cast and then add something to ids which is not a MyCompany (perhaps MyPerson which also implements HasId). So if the cast was allowed then you could do this.

public void myMethod(List<MyCompany> list){
    List<HasId> ids = list;
    ids.add(new MyPerson());
}

现在列表已经破坏了通用保证,因为您的列表已声明为 < MyCompany>

Now the list has broken the generic guarantee because you have list that was declared as <MyCompany> with a MyPerson in it.

b
$ b

You could cast it like this.

public void myMethod(List<MyCompany> list){
    List<? extends HasId> ids = list;
}

但不允许add()操作,如果你愿意,得到id。

But add() operations will not be permitted, but you can iterate it to get the id if you wish.

这篇关于Java参考分配与通用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆