arrayList Element Substitution

edited December 2016 in Questions about Code

the thing is I have an arraylist of objects (random PVectors), in which I want to subtitute the first element (index0) with another one with specific coordinates. But when I run the "display" function to call all the elements, I can´t see the "change" in the arrayList. why?

  ArrayList <Agent> a= new ArrayList<Agent>();
        int pop=10;
        int size=5;
        ///////////////////////////////////////////////////NEW PVECTOR
        PVector two= new PVector(width/2, height/2);
        Agent aa = new Agent(two, size);
       //////////////////////////////////////////////////NEW PVECTOR

        void setup() {
          size(400, 400); 

          for (int i=0; i<pop; i++) {
            PVector orig= new PVector(random(width), random(height));
            Agent ag = new Agent(orig, size);
            a.add(ag);
          }
          a.set(0, aa);////////////////////////////////////////////once PVector is added to ArraList a, this is not shown(?)
        }


        void draw() {
          background(0);

          for (int i=0; i<a.size(); i++) {
            Agent agent = a.get(i);
            agent.display();
          }
        }


        ////////////////////////////////////////////////////////////////////////////////////////////
        class Agent {
          PVector loc;
          int size;

          Agent(PVector _loc, int _size) {
            loc=_loc;
            size=_size;
          }

          void display() {
            fill(255);
            ellipse(loc.x, loc.y, size, size);
          }
        }

Answers

  • Answer ✓
    PVector two= new PVector(width/2, height/2);
    

    width and height aren't defined before size() is called

    so you aren't adding a dot in the middle of the screen, you are adding one in the top corner.

  • if you println(aa); and println(a.get(0)); you'll see they are the same so your replace code is working, just not with the position you expect.

  • ouch! thx;)

  • edited December 2016

    The meta-lesson here is:

    1. Always make complex assignments to global variables (eg involving width and height or other Processing variables) in setup(), not globally.
    2. In setup(), always call size() first.

    These are good habits, even when they aren't necessary, because then if you incorporate a variable like widthorheight into a working line later, it won't suddenly break your sketch.

Sign In or Register to comment.