Vectors and Java

A

Anand Gopinath

Hi,

I've got a question regarding Vectors and how it behaves when passed
around in functions.

Say I have a function foo that takes a vector v, and I pass off v to
another function to have stuff filled into it.

public int [] foo(Vector v )
{
...
return bar(v);
}

public int[] bar(Vector w )
{
...
w.add("something");
w.add("something else" );
return new int[] {1, 1};
}

The int[] is also needed by the caller of foo, so I can't return the
vector from bar after filling it up.

If foo is called from say the main function, will I get the things I
added into the vector from bar?

public static void main( String[] args )
{
Vector test = new Vector();
foo(test);

System.out.println(test.get(0) ); // should print out something
System.out.println(test.get(1) ); // should print out something else
}


I've tried it and the Vector test is empty when I get it back from foo.
Any suggestions would greatly help. Its not empty in foo if I changed it
to look like

public int [] foo(Vector v )
{
...
bar(v);
System.out.println( v.get(0) );
...
return new int[] {0,0};
}

Thanks,

Anand Gopinath
 
V

VisionSet

Anand Gopinath said:
Hi,

I've got a question regarding Vectors and how it behaves when passed
around in functions.

Same applies to all objects, methods get there own local copy of the object
reference, so changes to the object are reflected in the original, since it
is the same reference.
However, if the method you call does this:

void myMethod(MyObj obj) {
obj = new MyObj();
}

Then you change the reference and subsequent changes (such as adding objects
to your vector) will no longer be reflected in the original.

If this isn't the case with you, then perhaps we need a bit more code.
Because as your code stands (elipsi removed & static context error in main
corrected) it works fine.

[what is the plural of elipsis anyhow?]
 
A

Anand Gopinath

+However, if the method you call does this:
+
+void myMethod(MyObj obj) {
+ obj = new MyObj();
+}

Okay, I didn't think of that. Hmmm.

Here's what I did. The variable is assigned another vector. That's why
it doesn't work, now it makes sense.

I just extracted all the values out of the other vector after the call
to bar, and added those values to the one the main function called. That
makes it work fine.

+If this isn't the case with you, then perhaps we need a bit more code.
+Because as your code stands (elipsi removed & static context error in
main+corrected) it works fine.

Thanks for the help.

Anand Gopinath
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top