我们投射物体或参考物吗?

kob*_*rui 3 java

我的代码看起来像这样:

public class Hashtabledemo2 {

public static void main(String[] args) {

    Hashtable myCompay = new Hashtable(10);
    System.out.println("Add some employee objects to the hashtable..");

    Salary e1 = new Salary("Salary1", "Palo Alto, CA",
            1, 100000.00);
    Hourly e2 = new Hourly("Hourly2", "Cupertino, CA", 2, 100.00);

    Contractor e3 = new Contractor("Contractor3", "Milpitas, CA",3, 1000.00);

    myCompay.put(new Integer(e1.hashCode()), e1);
    myCompay.put(new Integer(e2.hashCode()), e2);
    myCompay.put(new Integer(e3.hashCode()), e2);

    System.out.println("The size of the hashtable is "+myCompay.size());

    int size = myCompay.size();

    for(int i=1;i<=size;i++){
    /* Note that the get() method of the  hashtable class returns a reference to the object
        that matches the given key:
         public Object get(Object key)
         */
        Employee current =  (Employee) myCompay.get(new Integer(i));



        if(current instanceof Hourly){ 
            ((Hourly) current).setHoursWorked(40);
        } else if(current instanceof Contractor){

            ((Contractor) current ).setDaysWorked(5);
        }
        current.computePay();
        current.mailCheck();

    }
Run Code Online (Sandbox Code Playgroud)

薪水,小时和承包商都扩展了员工类.在我的理解中,我们将父项引用转换为子项,而不是相反.我不明白这行代码是如何工作的:

Employee current =  (Employee) myCompay.get(new Integer(i));
Run Code Online (Sandbox Code Playgroud)

这行代码用于获取存储在作为Salary对象的散列表的第一位置的对象.

myCompay.get(new Integer(i));
Run Code Online (Sandbox Code Playgroud)

之后,它被转换为Employee:

(Employee) myCompay.get(new Integer(i));
Run Code Online (Sandbox Code Playgroud)

然后分配给员工参考当前:

Employee current =  (Employee) myCompay.get(new Integer(i));
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释我们是否将存储在哈希表中的对象工资转换为员工对象,然后将其分配给员工参考current.or我们是否将引用e1转换为员工引用.有人解释一下发生了什么事.

das*_*ght 5

Java中对象和引用之间的区别有些模糊,因为访问对象的唯一方法是通过引用.进行强制转换时,可以将不同类型的引用引用到同一对象.

请注意,您的代码已损坏:它使用原始哈希代码将对象放入哈希表中,但随后它会尝试使用序列号将其检索回来.除非你很幸运,否则这不会起作用,其中一个对象会返回0..3范围内的哈希码.