The technique of introducing a generic method to solve the above problem is known as wildcard capture. Another example is a simple method that swaps the elements of a list from front to back. public void testWildcardCapture() { List<String> names = new ArrayList<String>(); names.add("alpha"); names.add("beta"); inPlaceReverse(names); assertEquals("beta", names.get(0)); assertEquals("alpha", names.get(1)); } static void inPlaceReverse(List<?> list) { int size = list.size(); for (int i = 0; i < size / 2; i++) { int opposite = size - 1 - i; Object temp = list.get(i); list.set(i, list.get(opposite)); list.set(opposite, temp); } } The wildcard capture involves calling a new generic method, swap: public void testWildcardCapture() { List<String> names = new ArrayList<String>(); names.add("alpha"); names.add("beta"); inPlaceReverse(names); assertEquals("beta", names.get(0)); assertEquals("alpha", names.get(1)); } static void inPlaceReverse(List<?> list) { int size = list.size(); for (int i = 0; i < size / 2; i++) swap(list, i, size - 1 - i); } private static <T> void swap(List<T> list, int i, int opposite) { T temp = list.get(i); list.set(i, list.get(opposite)); list.set(opposite, temp); } By doing so, you are giving the wildcard a name. |