How can I write this method?
我该怎么写这个方法?
public static <T> void adds(List<T> k,int i)
{
T y;
List<T> g = new ArrayList<T>();
for(i=0;i<5;i++) {
y+= k.get(i));}
}
}
What should I use for the sum?
我应该用什么来计算总和?
I have tried declaring a type T as a variable to place the sum within it.
我已经尝试将类型T声明为变量以将总和放入其中。
1 个解决方案
#1
3
You can use a generic method that takes a BinaryOperator<T>
of the type to be summed and calls it to add in a reduce operation:
您可以使用一个泛型方法,该方法将要对的类型的BinaryOperator
public static <T> T sum(List<T> list, BinaryOperator<T> adder) {
return list.stream().reduce(adder).get();
}
And you can use it like this:
你可以像这样使用它:
List<String> s = Arrays.asList("1", "2", "3");
sum(s, (s1, s2) -> String.valueOf(Double.parseDouble(s1) + Double.parseDouble(s2))); //"6.0"
sum(Arrays.asList(1, 2, 3, 4), (a, b) -> a + b); //10
This allows the method to be free of type-specific "addition" logic (so String list can be concatenated, numbers added, etc.
这允许该方法没有特定于类型的“添加”逻辑(因此可以连接字符串列表,添加数字等。
#1
3
You can use a generic method that takes a BinaryOperator<T>
of the type to be summed and calls it to add in a reduce operation:
您可以使用一个泛型方法,该方法将要对的类型的BinaryOperator
public static <T> T sum(List<T> list, BinaryOperator<T> adder) {
return list.stream().reduce(adder).get();
}
And you can use it like this:
你可以像这样使用它:
List<String> s = Arrays.asList("1", "2", "3");
sum(s, (s1, s2) -> String.valueOf(Double.parseDouble(s1) + Double.parseDouble(s2))); //"6.0"
sum(Arrays.asList(1, 2, 3, 4), (a, b) -> a + b); //10
This allows the method to be free of type-specific "addition" logic (so String list can be concatenated, numbers added, etc.
这允许该方法没有特定于类型的“添加”逻辑(因此可以连接字符串列表,添加数字等。