gpt4 book ai didi

java - 如何在不创建新类也不修改类的情况下将 "append"新字段/数据放入对象中?

转载 作者:行者123 更新时间:2023-12-01 18:26:54 24 4
gpt4 key购买 nike

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

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

return ???;
}

最佳答案

您已经列出了好的替代方案 - 创建一个新类并更改 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;
}

关于java - 如何在不创建新类也不修改类的情况下将 "append"新字段/数据放入对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25816134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com