(Newb) setting individual pvector values in arraylist

edited February 2014 in Programming Questions

New to processing and I'm having trouble with syntax on how to set specific values (x, y, or z) in an arraylistof pvectors . simple example:

ArrayList<PVector> points;
points = new ArrayList<PVector>();
points.add(new PVector(1,2, 0));
points.add(new PVector(3,4, 0));
points.add(new PVector(5,6, 0));
points.add(new PVector(7,8, 0));

int i =2;
if(points.get(i).x - points.get(i).y < 0) {
  // points.z(i-1) = 1;    //obviously wrong
   println(points);
} 

I can get() pvector values easily out of the arraylist but have had no luck in setting specific values when the pvector is already in the arraylist. I have fiddled with a number of syntax variations of trying to update the specific value and variations using pvector set() to no avail. my project requires me to load the arraylist with pvectors (no problem), and then for loop through the arraylist (no problem) and set z value of pvector loop index(-1) depending on x and y values of pvector at loop index(1) (problem). Just can't figure out the syntax to change the z value at pvector index(-1).

Simplified example above and if I could figure out how to set pvector z value at arraylist index(-1), I would be golden. Have found lots of examples with set() and add(), but nothing showing setting of single value for pvector already in the arraylist.

Help is appreciated.

Answers

  • points.get(i-1).z = 1; ?

  • edited February 2014 Answer ✓
    // forum.processing.org/two/discussion/3055/
    // newb-setting-individual-pvector-values-in-arraylist
    
    final ArrayList<PVector> points = new ArrayList();
    
    points.add(new PVector(1, 2));  // idx 0
    points.add(new PVector(3, 4));  // idx 1
    points.add(new PVector(5, 6));  // idx 2
    points.add(new PVector(7, 8));  // idx 3
    
    int idx = 2;  // current index
    PVector p = points.get(idx);  // get PVector @ idx #2
    
    if (p.x - p.y < 0)  points.get(idx-1).z = 1;  // previous index
    
    println(points);
    
    exit();
    
  • Thank you. Definitely not obvious to use a get() to set.

  • edited February 2014
    • Just be aware that get() is a List method.
    • After that, we get a PVector's reference from the specified index above.
    • Then we finally can access those PVector's 3 fields -> x, y, z.
    • And of course, all available PVector's methods as well!
  • Thanks, makes sense. As I reread the language reference it says that get returns an object. That should have been a good enough clue for me that it wasn't just a getter returning a variable in the pvector.

Sign In or Register to comment.