Initiation of the Generic classes in the designer



  • Like this class.

    public class Dynemiclist<T> {
        private T[] data;
        private int count = 0;
    
    public Dynemiclist() {
        this(10);
    }
    
    private Dynemiclist(int size) {
        data = new T[size]
    
        count = 0;
    }
    

    }

    such initialization data = new T[size] Underlines the compiler,
    I read the article that I could do that. data = (T[]) new Object[size]; Why doesn't the first option work and do the second one?



  • In short, because Java is so built.

    Generic Java implemented through technology https://en.wikipedia.org/wiki/Type_erasure , she means there's nothing in progress. GenericJVM They don't know anything about them in principle, they only exist at the code writing stage and, at the time of the compilation, they are replaced by castes to the classes you indicate. And in the classes and methods you wrote Generic will be changed to the lower limit of a possible class, for example <T extends Number> to be replaced Numberif it's simple <T>Object♪ In the case of two restrictions, e.g. <T extends Iterable&Cloneable>to the first, in this case, Iterable

    The liabilities do not support https://en.wikipedia.org/wiki/Type_erasure because JVM needs to know the type of mass created and the compiler cannot identify the type at the compilation stage. And it happens because Array is an object and has a field class, and the masses of different classes have different meanings in the field of class. If this code is fulfilled:

    System.out.println(new String[]{}.getClass());
    System.out.println(new Object[]{}.getClass());
    

    The result will be:

    class [Ljava.lang.String;
    class [Ljava.lang.Object;
    

    That's why if you use it. (T[]) new Object[size]; You'll get it. ClassCastException♪ And there is, in the same way, a fundamental difference between all other cases, e.g., if you do:

    System.out.println(new ArrayList<String>().getClass());
    System.out.println(new ArrayList<Object>().getClass());
    

    We'll get it.

    class java.util.ArrayList
    class java.util.ArrayList
    

    So, the class didn't change and you could use Generic because in that case JVM doesn't need to know anything about Generic.

    I think you've read it, but look at the chapter again. https://docs.oracle.com/javase/tutorial/java/generics/erasure.html in official documentation.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2