[英]How do I make take an object out of a vector as it's original class?
In my program I have a class called Circles and a class called CircleList which is a vector of Circles. 在我的程序中,我有一个名为Circles的类和一个名为CircleList的类,CircleList是Circles的向量。
I can add and take away Circles to the list fine but when I try to use a circle from the list like so. 我可以在列表中添加和删除圆圈,但是当我尝试像这样从列表中使用圆圈时。
Circle test = CircleList.elementAt(0);
It fails as a Circle is expected but an object is found. 失败,因为预期会出现Circle,但是找到了对象。 Is there anyway I can fix this so it comes out of the vector back as a Circle rather than as an Object?
无论如何,我可以解决这个问题,使它从向量中以圆而不是对象的形式返回吗?
here is the start of the CircleList class with the constructor 这是带有构造函数的CircleList类的开始
import java.util.Vector;
public class CircleList
{
private Vector CircleList;
public CircleList()
{
CircleList = new Vector();
}
Try it like this 像这样尝试
public class CircleList {
private Vector<Circle> circleList;
public CircleList() {
circleList = new Vector<Circle>();
}
If you do this, the compiler knows that you'll only use circleList
for storing Circle
objects, not some other kind of object, and will therefore allow you to refer to anything that comes out of circleList
with a Circle
variable. 如果这样做,编译器就会知道您将只使用
circleList
来存储Circle
对象,而不是其他种类的对象,因此,您将可以使用Circle
变量来引用来自circleList
任何内容。
You might also consider using ArrayList
in place of Vector
. 您可能还考虑使用
ArrayList
代替Vector
。 The Vector
class does some additional synchronisation which you almost certainly don't need. Vector
类执行一些几乎不需要的附加同步。 For more details on this particular type of synchronisation and why you don't want it, I would suggest reading Jon Skeet's answer to Why is Java Vector class considered obsolete or deprecated? 有关这种特定类型的同步以及为什么不希望使用它的更多详细信息,我建议阅读Jon Skeet的答案, 为什么Java Vector类被认为已过时或不推荐使用?
Well the problem is occuring when you are defining vector. 当您定义向量时,问题就出现了。
Please share the insertion code. 请分享插入代码。
However first try below code snippet for inserting elements into vector. 但是,首先尝试在下面的代码片段中尝试将元素插入向量。
Vector<Circle> CircleList = new Vector<Circle>(50);
CircleList.add(circle1);
CircleList.add(circle2);
........................
Then retrieve the element. 然后检索元素。
Circle test = CircleList.elementAt(0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.