通用允许String对象作为整数

ans*_*tta 0 java string generics integer list

List listofinteger类型是Integer,但接受String对象当我做检查instance of Integer,这是给真正的,它太奇怪了,有谁能够解释发生了什么.

我只知道当我发送List listofinteger到方法,它被赋予参考列表中没有任何类型的引用变量,当我添加需要输入字符串,现在当我返回List listofanythingList of Integer type,就应该接受,因为它的参考.

现在,但我检查instanceof,这是印刷trueInteger,但它的String.

import java.util.ArrayList;
import java.util.List;

public class TestEx {

     List<Integer> listofinteger=new ArrayList<Integer>();      //list of integer type
     public static void main(String... args)
     {

         TestEx f=new TestEx();
         f.listofinteger.add(123);              //adds integer by wrapping it(auto)

         f.listofinteger=f.addelement(f.listofinteger);

         if(f.listofinteger.get(1) instanceof Integer);
         {
             System.out.println("true");                   //prints true here
             System.out.println(f.listofinteger.get(1));
         }



     }
      List<Integer> addelement(List listofanything)
     {
          listofanything.add("asdasdasd");            //adding String object

        return listofanything;
     }
}    
Run Code Online (Sandbox Code Playgroud)

我知道addelement(List listofanything )这里的方法应该给出一个Integer类型,但我在这里测试它,以了解泛型的概念

Bob*_*der 5

首先,正如@VJD评论的那样,你有一个语法错误 - 不需要;:

if(f.listofinteger.get(1) instanceof Integer);
Run Code Online (Sandbox Code Playgroud)

关于您的问题,泛型是编译时间工具,用于检查类型安全性.在运行时,没有类型擦除的验证.这就是为什么你没有错误添加String到列表Integers..