Java:向量中的对象(Java: Objects in vectors)

编程入门 行业动态 更新时间:2024-10-26 12:32:45
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 older

It'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

更多推荐

本文发布于:2023-07-31 05:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1341889.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   对象   Java   Objects   vectors

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!