Sum of Ints by merging

Viewed 57

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;
    }
}
2 Answers

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.

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();
            }
        });
Related