需要Java向量操作说明

时间:2014-08-12 11:05:28

标签: java vector casting

我是一名Java初学者,试图将java程序翻译成另一种语言,并非常感谢下面代码的最后一行所执行操作的解释。请尽可能详细。任何见解都非常有价值。

class vector1 {
Vector first = new Vector();
}

public name {
int a = 1;
Vector last = new Vector();
num1 = ((vector1)last.elementAt(a)).first.size();
}

2 个答案:

答案 0 :(得分:0)

我认为这可以回答,尽管代码可靠的不可编辑......

最后一行检索a向量的last第(1)个元素,将其强制转换为vector1类型,然后检索first字段并查询它因为它的大小。*

更容易理解的重写可能是:

vector1 v = (vector1) last.elementAt(a);
num1 = v.first.size();

由于代码isn't using generics,我们不知道向量中的对象类型。此代码使用强制转换来告诉编译器您确定该对象是vector1类型。这允许您访问该类的字段。

* 当然,这将失败,因为首先没有任何东西被放入载体中。

答案 1 :(得分:0)

在这里

import java.util.Vector;

class vector1 { //classes should be capitalized

    Vector  first   = new Vector();

    public void name() { //methods must have a return type 
                         //(even if it's void) and must have input parameters between ()

        int a = 1; //java statements end with ;
        Vector last = new Vector(); //java statements end with ;        

//      int num1 = ((vector1) last.elementAt(a)).first.size();

        /*
         * this is the same as
         */     

        Object lastElement = last.elementAt(a); //this is the second element from "last" 
                                                //because the first element's index is 0 
                                                //Since "last" is empty, you'll get an error here

        vector1 v = (vector1)lastElement; //now you're forcing the compiler to assume that lastElement is a Vector
        Vector v2 = v.first;              //now you're getting vector's attribute "first", which is another Vector
        int num1 = v2.size();             //now you're calling the method size() on v.first to get the vector number of elements
    }
}