0

In my program I have a class called Circles and a class called CircleList which is a vector of 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. 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

import java.util.Vector;
public class CircleList
{
    private Vector CircleList;

    public CircleList()
    {
    CircleList = new Vector();
    }
Sam
  • 454
  • 4
  • 18

2 Answers2

4

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.

You might also consider using ArrayList in place of Vector. The Vector class does some additional synchronisation which you almost certainly don't need. 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?

Community
  • 1
  • 1
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • Thankyou, this was really helpful. I'd also like to mention I would be using arraylists where possible but the exercise on my course asked to use a vector which is why I did. Thanks again. – Sam Dec 08 '13 at 17:11
0

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);
Encyclopedia
  • 134
  • 1
  • 9