Wildcard Capture Helper Swap Method
Swap two elements through a private capture helper that accepts List<?> and re-types it to <T>, since wildcard captures cannot be named directly.
Code
import java.util.ArrayList;
import java.util.List;
public class WildcardSwap {
// 通配符捕获助手 (capture helper):对外签名只能写 List<?>,
// 但 ? 不是类型,无法声明临时变量或做 set(i, get(j)),所以转交给 <T> 接住
private static <T> void swapCapture(List<T> list, int i, int j) {
// set(j, get(i)) 返回 j 处旧元素,再放到 i:一次交换、两次 set
list.set(i, list.set(j, list.get(i)));
}
public static void swap(List<?> list, int i, int j) {
swapCapture(list, i, j);
}
public static void main(String[] args) {
List<String> deck = new ArrayList<>(List.of("alpha", "beta", "gamma"));
swap(deck, 0, 2);
System.out.println(deck);
List<Integer> scores = new ArrayList<>(List.of(10, 20, 30));
swap(scores, 1, 2);
System.out.println(scores);
}
}Wildcard Capture Helper Swap Method: reading the source
Wildcard Capture Helper Swap Method keeps everything in the class WildcardSwap and the functions swapCapture, swap and main.
Caveats
- No lockfile entry, no version pinning — the file needs nothing beyond the runtime.
Applying it
Copy-adapted entry: private static <T> void swapCapture(List<T> list, int i, int j)
Running the file executes main, which drives swap in order.
Statements that matter
List<String> deck = new ArrayList<>(List.of("alpha", "beta", "gamma"));
List<Integer> scores = new ArrayList<>(List.of(10, 20, 30));
list.set(i, list.set(j, list.get(i)));
Interactive Tools for This Topic
FAQ
- How do you run Wildcard Capture Helper Swap Method?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.