There is a Set accepting in the constructor an array of Numbers and a summator method that adds all the numbers from the collection. I’m confused that the code for summation is repeated ... can it be somehow more beautiful to solve this problem ... perhaps with the help of generics? I tried to write generic code and parameterize the class, but in this form it also does not work
/* T sum = null; for (T element : setNumbers) sum += element; return sum; */ Or it is impossible in principle to use generics here? and you need to look for a beautiful solution in working with Collections or stream api, some lambda .... Prompt the direction at least. I bring my code ...
private Set<Number> numbers; private Class type; public MathBox(Number[] numbers){ if (numbers[0] instanceof Integer) this.type = Integer.class; if (numbers[0] instanceof Long) this.type = Long.class; if (numbers[0] instanceof Double) this.type = Double.class; if (numbers[0] instanceof Float) this.type = Float.class; this.numbers = new HashSet(Arrays.asList(numbers)); } public Number summator() { if (type == Integer.class) { Integer sum = 0; for (Number element : numbers) sum += (Integer) element; return sum; } if (type == Long.class) { Long sum = 0L; for (Number element : numbers) sum += (Long) element; return sum; } if (type == Double.class) { Double sum = 0.0; for (Number element : numbers) sum += (Double) element; return sum; } if (type == Float.class) { Float sum = 0.0F; for (Number element : numbers) sum += (Float) element; return sum; } return null; }