How to add PVectors into 2D Arraylist?

edited May 2016 in Questions about Code

Hey guys,

I would like to dynamically add new triangles (defined by its vertexes being PVectors). I don't know how many triangles I will have, so I would like to use a 2D Arraylist.

How do I add elements to this double array? My code doesn't work because array.get(i) (obviously) returns null. How do I add a new PVector to i,j?

Here is my code so far:

ArrayList<ArrayList<PVector>> array = new ArrayList<ArrayList<PVector>>();

void setup()
{
  for (int i=0; i<1; i++) {           
    for (int j=0; j<3; j++) {   
      array.get(i).get(j).add(new PVector(0, 0, 0));
    }
  }

  for (int i=0; i<array.size(); i++) {         
    for (int j=0; j<array.get(i).size(); j++) {  
      println(array.get(i).get(j).x);
    }
  }
}

Thanks for any reply:)

(I have found this discussion but I'm missing the iterration: https://forum.processing.org/one/topic/2d-arraylist.html)

Answers

  • Answer ✓

    When yoi have a ClassTriangle your ArrayList could be of that type

    Much easier (in the longrun)

  • Thank you for that answer, Ill try to do it that way:)

    However, if anyone is interested in a more generic solution, I made it work:

    ArrayList<ArrayList<PVector>> array = new ArrayList<ArrayList<PVector>>();
    
    void setup()
    {
      for (int i=0; i<2; i++) { 
        array.add(new ArrayList<PVector>());
       for (int j=0; j<3; j++) {   
         array.get(i).add(new PVector(i, 0, j));  //.get(j).add(new PVector(0, 0, 0));
       }
      }
    
      for (int i=0; i<array.size(); i++) {         
        for (int j=0; j<array.get(i).size(); j++) {  
          println(array.get(i).get(j));
        }
      }
    }
    
  • edited May 2016 Answer ✓

    @szemy2, you can replace the internal ArrayList<PVector> w/ just PVector[]: *-:)

    // forum.Processing.org/two/discussion/16383/
    // how-to-add-pvectors-into-2d-arraylist
    
    // GoToLoop (2016-May-02)
    
    import java.util.List;
    
    static final int VERTS = 3;
    final List<PVector[]> trigs = new ArrayList<PVector[]>();
    
    void setup() {
      for (int i = 0; i < 2; ++i) {
        trigs.add(new PVector[VERTS]);
    
        for (int j = 0; j < VERTS; ++j)
          trigs.get(i)[j] = PVector.random2D(this);
      }
    
      for (final PVector[] t : trigs)  println(t);
      exit();
    }
    
Sign In or Register to comment.