What is the concept of erasure in generics in Java?

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

What is the concept of erasure in generics in Java?

8条回答
  •  面向向阳花
    2020-11-22 02:10

    Erasure, literally means that the type information which is present in the source code is erased from the compiled bytecode. Let us understand this with some code.

    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    public class GenericsErasure {
        public static void main(String args[]) {
            List list = new ArrayList();
            list.add("Hello");
            Iterator iter = list.iterator();
            while(iter.hasNext()) {
                String s = iter.next();
                System.out.println(s);
            }
        }
    }
    

    If you compile this code and then decompile it with a Java decompiler, you will get something like this. Notice that the decompiled code contains no trace of the type information present in the original source code.

    import java.io.PrintStream;
    import java.util.*;
    
    public class GenericsErasure
    {
    
        public GenericsErasure()
        {
        }
    
        public static void main(String args[])
        {
            List list = new ArrayList();
            list.add("Hello");
            String s;
            for(Iterator iter = list.iterator(); iter.hasNext(); System.out.println(s))
                s = (String)iter.next();
    
        }
    } 
    

提交回复
热议问题