Код: Выделить всё
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
class GenericMultiplier {
public List multiplyByTwo(List list) {
List resultList = new ArrayList();
for (T item : list) {
// Perform multiplication based on the type of Number
if (item instanceof Integer)
resultList.add((T) Integer.valueOf(item.intValue() * 2));
else if (item instanceof Double)
resultList.add((T) Double.valueOf(item.doubleValue() * 2));
}
return resultList;
}
}
public class Main {
public static void main(String[] args) {
List intList = Arrays.asList(1, 4, 6, 87, 34);
GenericMultiplier multiplier = new GenericMultiplier();
List doubledList = multiplier.multiplyByTwo(intList);
System.out.println("Original List: " + intList);
System.out.println("Doubled List: " + doubledList);
}
}
Код: Выделить всё
Type safety: Unchecked cast from Double to TКод: Выделить всё
Type safety: Unchecked cast from Integer to TПодробнее здесь: https://stackoverflow.com/questions/786 ... s-warnings
Мобильная версия