Java:向量中的对象

时间:2016-01-12 11:12:30

标签: java oop

Vector v = new Vector();
String element = "Object"
v.add(element);

char c = ((String)v.get(0).charAt(0);

如果向量包含的引用指向现在为String的正确对象,为什么我们需要将元素强制转换为element以使用String的方法?

2 个答案:

答案 0 :(得分:2)

这是因为您没有声明Vector的元素类型,因此编译器假定元素只是Objects。试试这个:

Vector<String> = new Vector<>(); // new Vector<String>() if you're using Java6 or older

答案 1 :(得分:1)

As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.

Source: Java Vector API

As people above already mentioned, you do not specify what type of Object will your Vector contain. Therefore, Java assumes the elements in your Vector are of type Object which is the most generic type. Therefore, you'd be required to cast it into an appropriate type in order to carry out type specific operations.

I would encourage you to go onto the link provided above to learn more about the collection you are planning to use.