ArrayStoreException in java arrays

This is an example in a Core Java book.

Two-class employee and manager. Manager extends Employee. Code below

Manager[] mans ={new Manager("Adam"),new Manager("Ben")};              
Employee[] emps =mans ;   
emps[0] = new Employee ("Charlie");//throws ArrayStoreException in runtime actually;

The author said that in this situation, elements in arrays MUST STAY ONE TYPE , or he throws an ArrayStoreException. In my opinion, emps [0] is just a reference to the instance of "New Employee" ("Charlie") "and the type emps [0] is the Employee declared earlier. Therefore, why it throws an exception.Is something wrong with my basics?

+4
source share
3 answers

When an array is created, it remembers what type of data it is intended for storage. So, if you have classes

class Employee { .. }
class Manager extends Employee { .. }

and you will create an array

Manager[] arrM = new Manager[10];
Array

, Manager . , Manager, -

arrM[0] = new Manager();

,

arrM[0] = new Employee();

throws java.lang.ArrayStoreException: Employee , Employee .

,

  • Manager[] mans ={new Manager("Adam"),new Manager("Ben")};
    
  • Employee

    Employee[] emps =mans;
    

    ( , Menagers)

  • new Employee

    emps[0] = new Employee("Charlie");
    

, , , , Employee , . , Menager hire(...) -, Employee ( ). ,

    mans[0].hire(new Employee("Tom");

emps[0] = new Employee ("Charlie"); , Employee emps[0]? mans emps , , mans[0].hire(new Employee("Tom") Employee("Charlie"), -, Employee hire.

(Employee) .

+4

(Manager [] mans) (Employee[] emps). ... emps

Manager[]

Employee[], sitll Manager.

, emps[0] Manager.

0

, , , . Employee[] emps = mans; , emps Manager. , , .

Interestingly, if you created an array manswith a size of 1 (you don’t know what you would do this, perhaps ArrayListif you plan to expand it later), and then the rest of your code is followed, what would happen. I bet it still won't let you paste Employeeinto an array.

0
source

Source: https://habr.com/ru/post/1544490/


All Articles