0

I have a variant-style object foo that is capable of behaving as a java.util.Map and a java.util.List as well as other plain-old-data types. This object is written in C++ (modelled on the composite pattern) and I'm building a JNI so that I can use it in Java.

In Java, I'm motivated to write

public class foo implements 
        Streamable, 
        java.util.Map<String, foo>,
        java.util.List<foo>

Then I encounter trouble. For example, I need to implement 3 flavors of remove:

public foo remove(int index)   
public boolean remove(Object key)   
public foo remove(Object key)

The first two are for java.util.list, the final one for java.util.map. This, of course, is a problem since you cannot have two functions with the same name and parameters but different return types.

Is there a way round this?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Bathsheba
  • 231,907
  • 34
  • 361
  • 483

2 Answers2

0

You could use a LinkedHashMap.

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries.

Please refer to this question as it discusses the same problem you're having.

Community
  • 1
  • 1
Bruno Toffolo
  • 1,504
  • 19
  • 24
0

An adapter would work. Have one class implement Map and Stream, and another class implement List and Stream. All operations required by these adapter's respective interfaces would draw from a common underlying foo instance.

William Morrison
  • 10,953
  • 2
  • 31
  • 48
  • Yes this is probably the best you can do given that my idea, on reflection, is fundamentally illogical. So +1 and accept. – Bathsheba Jan 29 '14 at 19:35
  • Could someone explain the -1 here? Also, @Bathsheba, I would recommend you refactor so `foo` doesn't implement these drastically different interfaces. I understand you're following a composite design pattern, but when the interface's behavior are so fundamentally different, I advise against it. Instead, try creating 3 separate adapters implementing Stream, list, and map, backed by the same data source. I'd be interested in your reasoning in implementing Map, and Stream on one object if you'd care to elaborate. – William Morrison Jan 30 '14 at 16:12
  • 1
    In the end I went for coercion methods like `asList()` and `asMap()` which return concrete standard java types. They fitted quite well with other methods like `asString()` and `asDouble()` which I already had. Your answer certainly put me on the right track. – Bathsheba Jan 30 '14 at 16:19
  • Ah, great, I'm glad to hear it! – William Morrison Jan 30 '14 at 16:27