英文:
Sum of Ints by merging
问题
public class SomeClass {
int a = 0;
int b = 0;
int c = 0;
// ...
public void mergeValues(final SomeClass other) {
this.a += other.a;
this.b += other.b;
this.c += other.c;
// .....
return this;
}
}
英文:
The essence:
There is a class with int fields (from 1 to infinity). This class has a method that adds these values with another instance of this class. Question: Is it possible to do it somehow more elegantly?
Code:
public class SomeClass {
int a = 0;
int b = 0;
int c = 0;
...
public void mergeValues(final SomeClass other) {
this.a += other.a;
this.b += other.b;
this.c += other.c;
.....
return this;
}
}
答案1
得分: 1
你可以将这些整数存储在一个映射中。因此,你从字符/字符串映射到整数。然后,对于另一个类映射中的每个键,你将该值添加到该类映射中相应值的位置。类似以下示例。我已经有一段时间没有使用过 Java,但是思想应该是相同的。
for (Map.Entry<Integer, String> set : other.getMap().entrySet()){
this.map.put(set.getKey(), set.getValue() + this.map.get(set.getKey()));
}
另外,你也可以使用反射来迭代遍历所有字段。请参阅这里。
英文:
You can store these integers in a map. So you map from char/string to int. So then for each key in the other class's map, you add that value to the corresponding value in this class's map. Something like the following. It's been a while since I've used java, but the idea should be the same.
for (Map.Entry<Integer, String> set : other.getMap().entrySet()){
this.map.put(set.getKey(), set.getValue()+ this.map.get(set.getKey()))
}
Otherwise, you can use reflection to iterate over all of the fields. See here.
答案2
得分: 1
Arrays.stream(getClass().getDeclaredFields()).forEach(n -> {
try {
long temp = n.getLong(this);
temp += oc.getClass().getDeclaredField(n.getName()).getLong(oc);
if (n.getType().isAssignableFrom(int.class)) {
n.setInt(this, (int) temp);
} else if (n.getType().isAssignableFrom(long.class)) {
n.setLong(this, temp);
}
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
});
英文:
Arrays.stream(getClass().getDeclaredFields()).forEach(n -> {
try {
long temp = n.getLong(this);
temp += oc.getClass().getDeclaredField(n.getName()).getLong(oc);
if (n.getType().isAssignableFrom(int.class)) {
n.setInt(this, (int) temp);
} else if (n.getType().isAssignableFrom(long.class)) {
n.setLong(this, temp);
}
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论