我正在尝试寻找减少代码重复的方法。像这段代码一样,我的课堂上有多个Map元素。请给我建议,如果您有东西..!
public Class MyObject{
private Map map1;
private Map map2;
private Map map3;
//having setter/getter
}
importDatabase(){
//here i have data in the map1, map2, map3 elements
importMap(MyObject.getMap1());
importMap(MyObject.getMap2());
importMap(MyObject.getMap3());
}
importMap(Map map){
//want to insert map objects into database at one go, instead of creating 3 methods for each type
Iterator iterator = map.values().iterator;
while(iterator.hasNext(){
}
}
如果您有许多相同类型的相似对象(在您的情况下为maps),并对所有对象执行相同的操作(将它们放入数据库中),一种简单且通常可行的避免重复的方法是:将它们存储在array或ArrayList中(如果您事先不知道它们有多少个),并在for或foreach循环中执行操作。
使用三个元素并不总是值得付出努力,实际上可以使代码的可读性比以前降低。这只会使您的代码更短,而不会提高性能(我想这就是您使用[[一次性使用的意思)。]