views:

421

answers:

2

Coming from a C# Background I never used any pointers.

I'm creating a vector of contacts objects. What is the best way to create a separate vector which references to elements in the big vector?

+2  A: 

You can iterate through the old Vector and add the elements to a new Vector.

Vector oldVector;
Vector newVector = new Vector(oldVector.size());

for (int i = 0; i < oldVector.size(); i++){
    // add logic to exclude items from the new vector if you need
    newVector.add(oldVector.get(i));
}

Now, both vectors contain references to the same objects. Calling:

newVector.get(n).modifyInSomeWay();

The change will be reflected in both lists.

jjnguy
Ty for the syntax error fix!
jjnguy
I don't want to copy elements.
Henrik P. Hessel
This doesn't copy elements.
jjnguy
Okay, maybe I misunderstood the concept of a Vector. A Vector always contains references?!
Henrik P. Hessel
Exactly .
jjnguy
+1  A: 

Just add the same object reference to both Vectors!

Contact myContact = getContact();

Vector vectorOne = new Vector();
Vector vectorTwo = new Vector();

vectorOne.add(myContact);
vectorTwo.add(myContact);

There is only one instance of myContact, but many references to it.

Harry Lime