What is the concept of erasure in generics in Java?

前端 未结 8 692
误落风尘
误落风尘 2020-11-22 01:45

What is the concept of erasure in generics in Java?

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 01:54

    There are good explanations. I only add an example to show how the type erasure work with a decompiler.

    Original class,

    import java.util.ArrayList;
    import java.util.List;
    
    
    public class S {
    
        T obj; 
    
        S(T o) {
            obj = o;
        }
    
        T getob() {
            return obj;
        }
    
        public static void main(String args[]) {
            List list = new ArrayList<>();
            list.add("Hello");
    
            // for-each
            for(String s : list) {
                String temp = s;
                System.out.println(temp);
            }
    
            // stream
            list.forEach(System.out::println);
        }
    }
    

    Decompiled code from its bytecode,

    import java.io.PrintStream;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.Objects;
    import java.util.function.Consumer;
    
    public class S {
    
       Object obj;
    
    
       S(Object var1) {
          this.obj = var1;
       }
    
       Object getob() {
          return this.obj;
       }
    
       public static void main(String[] var0) {
    
       ArrayList var1 = new ArrayList();
       var1.add("Hello");
    
    
       // for-each
       Iterator iterator = var1.iterator();
    
       while (iterator.hasNext()) {
             String string;
             String string2 = string = (String)iterator.next();
             System.out.println(string2);
       }
    
    
       // stream
       PrintStream printStream = System.out;
       Objects.requireNonNull(printStream);
       var1.forEach(printStream::println);
    
    
       }
    }
    

提交回复
热议问题