1

I have existing code that returns a List<Map<String, String>>.

I would like to create a class that replaces this but will still work for existing code.

I've tried a couple of things but I get a compile error that says either "cannont be implemented more that once" or my Data object cannot be converted to a List<Map<String, String>>.

Searching for answers I find things like the following but not how to do this specifically.

Extending Generic Classes

Java Code that gives "cannot be implemented more than once" error.
Data class

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Data extends ArrayList<Row> implements List<Map<String, String>> {

}

Row class

import java.util.HashMap;
import java.util.Map;

public class Row extends HashMap<String, String> implements Map<String, String> {

    public Integer getInt(String key) {
        return Integer.parseInt(this.get(key));
    }
    
}
John
  • 3,458
  • 4
  • 33
  • 54
  • 1
    You can't implement the same generic interface twice with different types. My suggestions: don't make the "new" interface an `List`, but make it have a method that *returns* a `List`. – Joachim Sauer Sep 19 '20 at 18:20
  • I'm thinking it might not be possible to make it seamlessly backwards compatible as existing code will be creating List> objects that cannot be cast (widened) to List objects. – John Sep 19 '20 at 18:30

1 Answers1

1

I think this is not possible in Java. Only one chanse to do this I think if you change function signature to accept List<? extends Map<String, String>> instead of List<Map<String, String>>. In this case this is possible:

public class Foo {

    public static void main(String[] args) throws ParseException {
        List<Map<String, String>> data1 = Collections.emptyList();
        Data data2 = new Data();

        foo(data1);
        foo(data2);
    }

    public static void foo(List<? extends Map<String, String>> data) {
    }
}

class Row extends AbstractMap<String, String> {

    public Integer getInt(String key) {
        return Integer.parseInt(this.get(key));
    }

    @Override
    public Set<Entry<String, String>> entrySet() {
        return null;
    }
}

class Data extends AbstractList<Row> {

    @Override
    public Row get(int index) {
        return null;
    }

    @Override
    public int size() {
        return 0;
    }
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35