英文:
How to write class to replace generic in Java that is backwards compatible?
问题
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Data extends ArrayList<Row> implements List<Map<String, String>> {
}
public class Row extends HashMap<String, String> implements Map<String, String> {
public Integer getInt(String key) {
return Integer.parseInt(this.get(key));
}
}
英文:
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.
https://stackoverflow.com/questions/7255643/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));
}
}
答案1
得分: 1
我认为在Java
中这是不可能的。我认为只有一种机会可以做到这一点,如果您将函数签名更改为接受List<? extends Map<String, String>>
而不是List<Map<String, String>>
。在这种情况下,这是可能的:
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;
}
}
英文:
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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论