How do arrays “remember” their types in Java?

前端 未结 5 516
情深已故
情深已故 2021-02-07 02:14

Consider the following code:

class AA { }

class BB extends AA { }

public class Testing {

    public static void main(String[] args) {
        BB[] arr = new B         


        
5条回答
  •  情深已故
    2021-02-07 02:55

    Arrays do explicitly remember their type, you can even get it at runtime (array.getClass().getComponentType()).

    When storing to an array, the VM will check if the element to be store is assignment compatible with the array's component type. If it isn't, you get ArrayStoreException.

    Collections (as ArrayList) do internally declare their backing arrays as Object[], thus they can store anything, even types they are not allowed to store by their generic definition.

提交回复
热议问题