我有这门课...
public abstract class LoadboardTable
{
protected Map<String, HashMap<HasTableFields, String>> table = new TreeMap<String, HashMap<HasTableFields, String>>();
public Set<Entry<String, HashMap<HasTableFields, String>>> getEntries()
{
return table.entrySet();
}
...
}
在其他类(class)中,我不断重复泛型类型。例如...
for (Entry<String, HashMap<HasTableFields, String>> entry : myTable.getEntries()){}
Set<Entry<String, HashMap<HasTableFields, String>>> entries = otherTable.getEntries();
etc, etc...
这种泛型类型在整个应用程序中重复出现并散乱。有没有更好的办法?如果我决定更改 LoadboardTable 类中表 Map 对象的通用类型,我也会在其他地方更改它几天。另外,继续输入是一件非常痛苦的事情。
最佳答案
从 Java 7 开始,除了构造函数之外,没有办法避免重复:
protected Map<String, HashMap<HasTableFields, String>> table = new TreeMap<>();
如果您将 HashMap 和条目封装在定义良好的类中,您将拥有更好的代码,并且需要更少的输入。看起来您正在使用对象作为开放数据结构,而不是使用它们作为提供行为并封装其状态的封闭对象。
关于java - 通用类型重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14503868/