为什么将这两种方法放在同一个类中是不合法的?
class Test{
void add(Set<Integer> ii){}
void add(Set<String> ss){}
}
Run Code Online (Sandbox Code Playgroud)
我明白了 compilation error
方法add(Set)具有与Test类型中的另一种方法相同的擦除add(Set).
虽然我可以解决它,但我想知道为什么javac不喜欢这个.
我可以看到,在许多情况下,这两种方法的逻辑非常相似,可以用一个方法代替
public void add(Set<?> set){}
Run Code Online (Sandbox Code Playgroud)
方法,但情况并非总是如此.
如果你想要有两个constructors接受这些参数的话,这是非常烦人的,因为那时你不能只改变其中一个的名字constructors.
我有一个相对复杂的泛型类型(比如说Map<Long,Map<Integer,String>>),我在课堂内部使用它.(没有外部可见性;它只是一个实现细节.)我想在typedef中隐藏它,但Java没有这样的功能.
昨天我重新发现了以下成语,并且对于被认为是反模式感到失望.
class MyClass
{
/* "Pseudo typedef" */
private static class FooBarMap extends HashMap<Long,Map<Integer,String>> { };
FooBarMap[] maps;
public FooBarMap getMapForType(int type)
{
// Actual code might be more complicated than this
return maps[type];
}
public String getDescription(int type, long fooId, int barId)
{
FooBarMap map = getMapForType(type);
return map.get(fooId).get(barId);
}
/* rest of code */
}
Run Code Online (Sandbox Code Playgroud)
当类型被隐藏并且不构成库API的一部分时(在我看来,Goetz对使用它的主要反对意见),是否有任何理由可以解决这个问题?
我有两种类型的列表:
ArrayList<String> sList;
ArrayList<Resource rList;
Run Code Online (Sandbox Code Playgroud)
我可以.getName()在资源对象上调用一个方法.
我想通过调用printList(list)这样的方法打印出这些列表中的任何一个:
printList(sList);
printList(rList);
Run Code Online (Sandbox Code Playgroud)
他们的代码看起来像这样:
private static void printList(ArrayList<String> list){
for(String s : list){
System.out.println(s + ", ");
}
}
private static void printList(ArrayList<Resource> list){
for(Resource r : list){
System.out.println(r.getName() + ", ");
}
}
Run Code Online (Sandbox Code Playgroud)
我没有任何特别的使用理由private static,它恰好是因为eclipse建议它.
但是,代码不起作用.Eclipse给出了以下错误:
"方法printList(ArrayList)具有与GUI类型中的另一种方法相同的擦除printList(ArrayList)"
GUI是我的班级.怎么了?
编辑:是否有任何替代或解决方案来获得我想要的功能?