Implement Map and List interface in Java?

I would like to have an object that implements Map and List interfaces in Java. The idea is similar to a problem in this question: Java Ordered Map

I want to add name / value pairs to the list and keep the list in sequence, but also be able to search 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 compilation error:

"The return type is incompatible with Map.remove(Object)"
public boolean remove(Object o) {
    return false;
}

If I do not implement the Map and List interfaces, then there are many Java collection methods that are not available for use in this data structure.

(In addition, the reason the solution proposed in the Java Ordered Map above does not work is because LinkedHashMap does not have a get (int) method. It is not possible to select records by index.)

+5
6

, List, Map . , , . , data Map, List. Map entrySet() Map.values ​​().

, 2 , List , Map.

(, ), List getAsList(), , .

. . , , , .

+5

LinkedHashMap , .

- . HashMap , , .

+5

, , Map remove:

V remove(Object key)

List :

boolean remove(Object o) 

Java , .

+5

?

public interface HashListMap {

public boolean add(Object arg0);
public void add(int arg0, Object arg1);
public boolean addAll(Collection arg0);
public boolean addAll(int arg0, Collection arg1);
public void clear();
public boolean contains(Object arg0); 
public boolean containsAll(Collection arg0);
public Object get(int arg0);
public int indexOf(Object arg0);
public boolean isEmpty();
public Iterator iterator();
public int lastIndexOf(Object arg0);
public ListIterator listIterator();
public ListIterator listIterator(int arg0);
public boolean remove(Object arg0);
public Object remove(int arg0);
public boolean removeAll(Collection arg0);
public boolean retainAll(Collection arg0);
public Object set(int arg0, Object arg1);
public int size();
public List subList(int arg0, int arg1);
public Object[] toArray();
public Object[] toArray(Object[] arg0);
public boolean containsKey(Object arg0);
public boolean containsValue(Object arg0);
public Set entrySet();
public Object get(Object arg0);
public Set keySet();
public Object put(Object arg0, Object arg1);
public void putAll(Map arg0);
public Collection values();

}

+2

Map List remove. , .

, List<Map.Entry<K,V>> .

+1

, , LinkedHashMap. , .

As a map, it implements the values ​​() method, so you can say a new ArrayList (map.values ​​()). get (0) to simulate the functionality of a list.

but you can also say map.get ("one") because it is just an implementation of the map.

+1
source

All Articles