# Thread: Can't access two vectors independantly?

1. Member
Join Date
Nov 2007
Posts
4
Rep Power
0

## Can't access two vectors independantly?

Hi I haven't used Vectors before but I can't work out what I'm doing wrong here. I have a class called PointSequence which contains a Vector of Points (and some methods to work with them). If I then create two instances of this class (or an array of two for that matter), adding something to one of them seems to add it to both.

Java Code:
```// A class for a sequence of Points
import java.awt.*;
import java.util.*;

public class PointSequence
{
static Vector <Point> points=new Vector <Point> (); //the x,y locations are stored in a vector which will grow as you add items

//i have some other methods here

public static void main(String[] args)
{
//create two instances of the new class
PointSequence testA=new PointSequence();
PointSequence testB=new PointSequence();

//add something to A

//add something different to B

//print out the contents of each instance
System.out.println("A contains...");
for(int i=0;i<testA.points.size();i++)
{
System.out.println(testA.points.elementAt(i));
}

System.out.println("B contains...");
for(int i=0;i<testB.points.size();i++)
{
System.out.println(testB.points.elementAt(i));
}
}
}```
This produces the following output:

A contains...
java.awt.Point[x=256,y=196]
java.awt.Point[x=100,y=100]
B contains...
java.awt.Point[x=256,y=196]
java.awt.Point[x=100,y=100]

Why do both have the same contents even though I added one item to each?!! Is there something fundamental I am misunderstanding about Vectors or classes?

Cheers:confused:

2. Marking the Vector with the static access modifier makes it a "class" object, ie, there is only one Vector object for each and every instance of PointSequence. Any instance can modify the vector and this modification will change the one "class" object for all instances. Removing the static access modifier from the declaration of the "points" Vector will allow each instance of PointSequence to have its own independent instance (object) of the vector.
For more discussion of this see Understanding Instance and Class Members.
Java Code:
```    // Try running PointSequence with and again without
// the [i]static[/i] access modifier for the Vector:
/*static*/ Vector<Point> points = new Vector<Point>();

// Add this test at the end of your class and see what happens
// when you make changes in the declaration of "points" above.
// Are these two vectore the same or equal?
System.out.printf("testA.points == testB.points      = %b%n" +
"testA.points.equals(testB.points) = %b%n",
testA.points == testB.points,
testA.points.equals(testB.points));```

3. Member
Join Date
Nov 2007
Posts
4
Rep Power
0
Great, I see now, thanks a bunch

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•