Java数组是同构的是什么意思,但ArrayLists不是?

如果我们有一个Type [],我们只能在其中存储Type或其子类型。 ArrayList也是如此。 那么为什么说一个是同质的而另一个不是呢?

数组对添加元素的类型进行运行时检查。 也就是说,如果添加了不同类型的新元素,则会在运行时抛出ArrayStoreException 。 这就是他们被认为是“家庭”的原因。

对于ArrayList (通常是List ),情况并非如此。 由于运行时类型擦除,它实际上可以容纳任何对象。

运行时以下引发exception:

 Object[] array = new String[3]; array[0] = "a"; array[1] = 1; // throws java.lang.ArrayStoreException 

不像以下编译和运行没有问题(虽然有编译器警告,因为它没有正确使用generics):

 ArrayList list = new ArrayList(); list.add("a"); list.add(1); // OK list.add(new Object()); // OK 

正确使用generics,即声明上面的类型为ArrayList而不是ArrayList的变量list ,在编译时避免了这个问题:

 ArrayList list = new ArrayList(); list.add("a"); list.add(1); // compilation error list.add(new Object()); // compilation error 

但即使使用一般声明的列表,您也可以在运行时使用此类工作而不会出现exception:

 ArrayList list = new ArrayList(); list.add("a"); Method[] methods = List.class.getMethods(); for(Method m : methods) { if(m.getName().equals("add")) { m.invoke(list, 1); break; } } System.out.println(list.get(0)); System.out.println((Object) list.get(1)); 

输出:

一个

1

是。 Java Arrays是同构的,因为当您在Java中声明任何数组时,您必须声明其type 。 例如:

 int arr[]; //type is int String arr[]; //type is String float arr[]; //type is float 

现在,如果您尝试在声明的数组中存储任何其他数据类型,则会出现编译时错误。 例如:

  int arr=new int[5]; arr[0]="I am a String not int"; //compile time error 

但是ArrayListCollection的一部分,它们持有Objects ,而不是任何特定的data-type [如果我们不讨论generics ],并且因为java中的每一个东西都直接或间接地从Object classinheritance,所以它不会给compile-time error,类型检查将在run-time

例如:

  ArrayList al=new ArrayList();//type is Object al.add("I am a String"); //Bacause String class in inherited from Object Class al.add(1);//the int 1 will first autobox into Integer class then stored in al ArrayList.Now bacause Integer class is also inherited from Object class,it will*/ allow you to store al.add(UserDefinedClass); //because every User defined class is also inherited from Object class,so it will also allow you. 

现在你注意到了,因为我们还没有定义任何数据类型的ArrayList al ,但我们仍然存储不同的类型值:这就知道为什么ArrayList Stores Object不是特定的数据类型,因此它们是异构的而不是同类的。