/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package generics; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; /** * * @author steve */ public class WildCard { // from https://www.baeldung.com/java-generics-vs-extends-object public static void printListObject(List list) { for (Object element : list) { System.out.print(element + " "); } } public static void printListWildCard(List list) { for (Object element : list) { System.out.print(element + " "); } } // A flexible copy operator for numbers // "PECS stands for producer-extends, consumer-super public static void copy(List from, List to) { to.clear(); for(int i=0;i goes after static // T is a comparable type // static void foo(List> foo) {} // error // static > void foo(List foo) {} // ok, but error for boos below static > void foo(List foo) {} static class Foo implements Comparable { int n; @Override public int compareTo(Foo that) { return this.n - that.n; } } static class Boo extends Foo {} public static void main(String[] args) { List data = Arrays.asList(3,4,5); // List lin = new ArrayList(); // error List lin = new ArrayList(); // ok List lin2 = Arrays.asList(1,2,3); copy(data, lin2); // printListObject(lin); // error printListWildCard(lin); if(data instanceof List) {} // ok // if(data instanceof List) {} // error if(lin instanceof List) {} // ok // foo(lin); // error foo(data); // ok List foos = new ArrayList<>(); foos.add(new Foo()); foo(foos); List boos = new ArrayList<>(); boos.add(new Boo()); foo(boos); } }