使用泛型与列表和接口的Java [英] Java using generics with lists and interfaces

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

问题描述



我有一个包含接口的列表 - List< Interface> a - 以及扩展该接口的接口列表: List< SubInterface> B'/ code>。我想设置 a = b 。我不希望使用 addAll()或任何会花费更多内存的东西,因为我正在做的事情已经非常昂贵。我实际上需要能够说 a = b 。我试过 List< ;?扩展界面>一个,但是我不能将接口添加到列表 a ,只有子接口。任何建议?



编辑



我希望能够做到这样的事情:

 列表< SubRecord> records = new ArrayList< SubRecord>(); 
//将事物添加到记录
recordKeeper.myList = records;

类RecordKeeper是包含接口列表(NOT subInterfaces)的元素

  public class RecordKeeper {
public List< Record>我的列表;
}

另外编辑:

我发布了我的工作解决方案。我感谢所有回答的人,并为显然使我的问题变得如此混乱而道歉。

因此,相当简单的解决方案的朋友我发现这是:

  recordKeeper.myList =(List< Record>)(List<?extends Record>)records; 

这可以理解,因为它需要宝宝的步骤。 列表< SubRecord> 列表< ;?扩展记录> 列表< ;? extends Record> 是一个 List< Record> 。这可能不太好,但它仍然有效。


Ok, so here is my problem:

I have a list containing interfaces - List<Interface> a - and a list of interfaces that extend that interface: List<SubInterface> b. I want to set a = b. I do not wish to use addAll() or anything that will cost more memory as what I am doing is already very cost-intensive. I literally need to be able to say a = b. I have tried List<? extends Interface> a, but then I cannot add Interfaces to the list a, only the SubInterfaces. Any suggestions?

EDIT

I want to be able to do something like this:

List<SubRecord> records = new ArrayList<SubRecord>();
//add things to records
recordKeeper.myList = records;

The class RecordKeeper is the one that contains the list of Interfaces (NOT subInterfaces)

public class RecordKeeper{
    public List<Record> myList;
}

ANOTHER EDIT:

I have posted my working solution. I thank everyone who answered, and apologize for apparently making my question so confusing.

解决方案

So, the rather simple solution a friend of mine found was this:

recordKeeper.myList = (List<Record>)(List<? extends Record>)records;

This works as I understand it because it takes baby steps. List<SubRecord> is a List<? extends Record>, and List<? extends Record> is a List<Record>. It might not be pretty, but it works nonetheless.

这篇关于使用泛型与列表和接口的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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