Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem about vector

 
sheng zhong
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.*;
public class test {

public static void main(String args[]){

Vector<Vector<Double>> Stree = new Vector<Vector<Double>>();
Vector<Double> Svec = new Vector<Double>();

Svec.add(100.0);
Stree.add(Svec);
Svec.add(200.0);
Stree.add(Svec);


System.out.println("Stree 0 is "+Stree.get(0));
System.out.println("Stree 1 is "+Stree.get(1));
}
}


The output are same, it's different from C++ result. I think it's the reason about java passing by reference, not a copy. So how can I do to make it output 100 and 200?
 
Nickolas Case
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I ran your code and got this as the output...

Stree 0 is [100.0, 200.0]
Stree 1 is [100.0, 200.0]

I am not sure what question you are asking? Are you only wanting just the 100.0 for Stree 0 and 200.0 for Stree 1? Or do you not want the decimals?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sheng zhong:
... The output are same, it's different from C++ result. I think it's the reason about java passing by reference, not a copy. So how can I do to make it output 100 and 200?

Java does not pass by reference. It passes by value (reference copies).

I'm not sure what you mean by "make it output 100 and 200." Are you looking for something like this...?

Stree.get(0).get(0)
Stree.get(1).get(1)
[ April 26, 2008: Message edited by: marc weber ]
 
sheng zhong
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, sorry for the misunderstanding. I am looking for the result like this:

Stree 0 is [100.0]
Stree 1 is [100.0] [200.0]

Since Svec changed before adding to Stree
[ April 26, 2008: Message edited by: sheng zhong ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So instead of adding a Svec reference, you want to add a "snapshot" of what Svec looks like at the moment it's added.

I suppose you could clone Svec each time you add it.

[ April 26, 2008: Message edited by: marc weber ]
 
sheng zhong
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by marc weber:
So instead of adding a Svec reference, you want to add a "snapshot" of what Svec looks like at the moment it's added.

I suppose you could clone Svec each time you add it.


[ April 26, 2008: Message edited by: marc weber ]



Thanks, that's exactly the answer I am looking for.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic