Why does this template work?

I am confused by this code, which is supposed to not work (I think), but doesn't seem to work without errors.

When I put <T>next to the Person class, the wildcard in Arraylist does not behave as it is defined, in the code below the wildcard should work only for the superPerson class , but <T>next to the Person class, it accepts all types for types (in this an example of this String). And also, in order for this to work, a person, when defined, should not have the specified type. Here is the code:

import java.util.ArrayList;

public class Person {
    public static void main(String[] args) {
        Human h = new Human();
        h.al(new ArrayList<String>()); // this should give an error no ?
    }
}

class Human<T>{ //Human is a generic class, but above I created an instance without specifying the T
    public void al(ArrayList<? super Person> a){ //the type passed should be a super of Person

    }
}

Thank:)

+4
source share
2 answers

Java Generics: , ?

:

, .

, , h Human, erasure h al ! , , .

. : Java generics - - .

, .

UPDATE

ClassCastException .

import java.util.ArrayList;
import java.util.Iterator;

class Human<T>{
  public void al(ArrayList<? super Person> a){
    Iterator<? super Person> iter = a.iterator();
    while (iter.hasNext()) {
      Person h = (Person) iter.next(); // unsafe cast
    }
  }
}

public class Person {
  public static void main(String[] args) {
    Human h = new Human();

    ArrayList<String> arr = new ArrayList<String>();
    arr.add("deadbeef");

    h.al(arr); // valid, since h is raw
  }
}
+4

<>, . :

Human<Object> h = new Human<>();

.

0

Source: https://habr.com/ru/post/1538331/


All Articles