Java:向量中的对象(Java: Objects in vectors)
Vector v = new Vector();
String element = "Object"
v.add(element);
char c = ((String)v.get(0).charAt(0);
如果向量包含的引用指向正确的String对象,为什么我们需要将元素转换为String来使用元素的方法?
Vector v = new Vector(); String element = "Object" v.add(element); char c = ((String)v.get(0).charAt(0);Why do we need cast the element as String to use the methods of the element if the references contained by the vector points to the proper object which is String now?
最满意答案
这是因为您没有声明Vector的元素类型,因此编译器假定元素只是Objects 。 试试这个:
Vector<String> = new Vector<>(); // new Vector<String>() if you're using Java6 or olderIt's because you're not declaring the element type of the Vector, so the compiler assumes that elements are just Objects. Try this:
Vector<String> = new Vector<>(); // new Vector<String>() if you're using Java6 or older更多推荐
发布评论