如何在不创建新类或修改类的情况下将新字段/数据“追加”到对象中?

时间:2014-09-12 20:13:56

标签: java

我有一个方法可以计算bean MyPeriod中每一行的整数。我不想更改类MyPeriod,创建新类或有两个列表,但我需要返回一些列表,其中包含MyPeriod列表和新列。有什么方法可以解决这个问题?

public ??? bindNewColumn (List<MyPeriod> periods) {
   List<Integer> newList = new ArrayList<>();
   for (MyPeriod period : periods) {
      newList.add(calculation(period));
   }

   return ???;
}

4 个答案:

答案 0 :(得分:2)

您列出了很好的选择 - 创建新课程并更改MyPeriod

如果你想要一个坏的,你可以返回一个数组,并让你的来电者认为它有两个项目:

// This is a very dirty approach. Do not use in production.
public List[] bindNewColumn (List<MyPeriod> periods) {
    ...
    return new List[] { periods, newList };
}

如果您知道List<MyPeriod>中的所有时段都不同,并且MyPeriod实现了强大的hashCode()equals(),那么您可以使用LinkedHashMap<MyPeriod,Integer>来建立你的映射:

public LinkedHashMap<MyPeriod,Integer> bindNewColumn (List<MyPeriod> periods) {
    LinkedHashMap<MyPeriod,Integer> res = new LinkedHashMap<MyPeriod,Integer>();
    for (MyPeriod period : periods) {
        res.put(period, calculation(period));
    }
    return res;
}

答案 1 :(得分:1)

如果您使用的是JDK7或更高版本,则可以使用javafx.util.Pair:

public Pair<List<MyPeriod>,List<Integer>> bindNewColumn (List<MyPeriod> periods) {
    ...
    return new Pair<List<MyPeriod>,List<Integer>>(periods,newList);
}

答案 2 :(得分:1)

使用Pair

public List<Pair<MyPeriod, Integer>> bindNewColumn(List<MyPeriod> periods) {
   final List<Pair<MyPeriod, Integer>> newList = new ArrayList<>();
   for (MyPeriod period : periods) {
      newList.add(Pair.of(period, calculation(period)));
   }

   return newList;
}

答案 3 :(得分:0)

public Map<MyPeriod, Integer> bindNewColumn (List<MyPeriod> periods) {
       Map<MyPeriod, Integer> map = new HashMap<MyPeriod, Integer>();
       for (MyPeriod period : periods) {
           map.put(period, calculation(period));
       }
       return map;
    }