Thursday, April 28, 2011

Java Vector : Secure reference to element

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?

From stackoverflow
  • 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!
    Henrik P. Hessel : I don't want to copy elements.
    jjnguy : This doesn't copy elements.
    Henrik P. Hessel : Okay, maybe I misunderstood the concept of a Vector. A Vector always contains references?!
    jjnguy : Exactly .
  • 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.

0 comments:

Post a Comment