2

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;
    }
}
Tenusha Guruge
  • 2,147
  • 3
  • 18
  • 38

2 Answers2

1

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.

fooiey
  • 1,040
  • 10
  • 23
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();
            }
        });