Skip to content

Instantly share code, notes, and snippets.

@kamekoopa
Created May 19, 2017 02:39
Show Gist options
  • Save kamekoopa/c2b9c4ab740799fd5398ec9962d8864d to your computer and use it in GitHub Desktop.
Save kamekoopa/c2b9c4ab740799fd5398ec9962d8864d to your computer and use it in GitHub Desktop.
型クラス.java
public class TypeClass {
interface Addable<T> {
T add(T a, T b);
}
public static class IntAdd implements Addable<Integer> {
@Override
public Integer add(Integer a, Integer b) {
return a + b;
}
}
public static class StringAdd implements Addable<String> {
@Override
public String add(String a, String b) {
return a + b;
}
}
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(1 ,2, 3);
List<String> stringList = Arrays.asList("a", "b", "c");
Integer result1 = addAll(integerList, 0, new IntAdd());
String result2 = addAll(stringList, "", new StringAdd());
}
public static <T> T addAll(List<T> list, T init, Addable<T> addable) {
T result = init;
for(T x : list){
result = addable.add(result, x);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment