在Java中实现Map和List接口? [英] Implement both Map and List interface in Java?
问题描述
我想要一个实现Java和Map接口的对象。此想法与此问题中的问题类似: Java有序映射
我想向列表中添加名称/值对,并让列表保留序列,但也可以按名称进行查找:
foo.put(name0,value0);
foo.put(name1,value1);
foo.get(1); - > Map.Entry(name1,value1)
foo.get(name0); - > value0
这里有问题:当我创建这个类:
类Foo实现Map,List {
//在此添加所有方法
}
我得到一个编译错误:
类型与Map.remove(Object)不兼容
public boolean remove(Object o){
return false;
}
如果我不实现Map和List接口,
(此外,上述Java有序映射中提出的解决方案不工作的原因是Linked HashMap没有get(int)方法,不能通过索引选择条目。)
您不能在同一个类上实现 List
和 Map
。但对于你所需要的,也不是必要的。你需要的是数据
可以通过 Map
和 / code>接口。有点像访问映射
数据集Map.html#entrySet%28%29rel =nofollow> entrySet()或作为集合使用 Map.values()。
总之,你需要对数据有2个视图,一个视图实现 List
,另一个视图实现 Map
。
如果有一个视图占优势(例如Map),那么你可以给你的map实现一个方法 List getAsList()
将数据作为List,由Map的数据支持。
编辑
Paulo Guedes给出的答案应该为您服务。已经有一个Map实现与您的要求。我的答案有点更一般,关于使用多个不兼容的接口提供相同的数据,其中一个简单的适配器是不够的。
I'd like to have an object that implements both the Map and the List interfaces in Java. The idea is similar to the problem in this question: Java Ordered Map
I want to add name/value pairs to a list and have the list preserve the sequence, but also be able to do lookups by name:
foo.put("name0", "value0");
foo.put("name1", "value1");
foo.get(1); --> Map.Entry("name1", "value1")
foo.get("name0"); --> "value0"
Here's the problem: when I create this class:
class Foo implements Map, List {
// add all methods here
}
I get a compile error:
"The return type is incompatible with Map.remove(Object)"
public boolean remove(Object o) {
return false;
}
If I don't implement the Map and List interfaces, then there are lots of Java collections methods that aren't available to use on this data structure.
(Also, the reason that the solution proposed in Java Ordered Map above doesn't work is that LinkedHashMap doesn't have a get(int) method. Can't select entries by index.)
As you noticed you cannot implement both List
and Map
on the same class. But for what you need that should also not be necessary. What you need is that the data
can be accessed by both a Map
and a List
interface. A bit like accessing Map
data as a set in entrySet() or as a Collection using Map.values().
In short, what you need is 2 views on the data, one view implementing a List
and another view implementing Map
.
If there is one view dominant (for example Map) then you could give your map implementation a method List getAsList()
which presents the data as a List, backed by the data of the Map.
EDIT
The answer given by Paulo Guedes should serve you. There already is a Map implementation with your requirements. My answer is a bit more general, about presenting the same data using multiple incompatible interfaces where a simple Adapter is not enough.
这篇关于在Java中实现Map和List接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!