Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 7 Next »

deutsche Version

https://processing.org/tutorials/arrays/

An array is a container that holds a fixed number of values, a bit like a spreadsheet table. With arrays we can store multiple variables of the same type, and access them easily.

int[] valueArray;
 
valueArray = new int[10];
println(valueArray.length);
 
for(int i=0; i < valueArray.length; i++) {
   valueArray[i] = i * 2;
 }
println(valueArray);

Arrays can also be imagined as drawers, with variables stored in each drawer. The drawer has a certain type, and each drawer store another set of draws (multidimensional). The individual drawers are numbered and start at 0. The size or the length is stored in the variable 'length'. Arrays are not dynamic, that means they can not change their length at runtime. If you need a dynamic array, you should use ArrayList.

ArrayList<Integer> numberList;
 
numberList = new ArrayList<Integer>();
println(numberList.size());
 
for(int i=0;i < 10;i++) {
   numberList.add(i * 2);
 }
println(numberList);
 
numberList.add(100);
println(numberList.size());
println(numberList);
 
numberList.remove(0);
println(numberList.size());
println(numberList);

println(numberList.get(0));

Unlike arrays, ArrayLists can only be one dimension.

Exercise 8.2

Use an array or ArrayList to draw animated icons on the screen.


Exercise 8.2 possible solution
int[] puffsX = new int[60];
int[] puffsY = new int[60];
 
int currentPuff= 0;
float angle = 0;
void setup() {
  size(600,600);
  noStroke();
}
 
void draw() {
  background(0);
 
  for(int i = 0; i < puffsX.length; i++) {
    DrawPuff(puffsX[i],puffsY[i],i);
  }
  angle+= 0.1;
}
 
void DrawPuff(int x, int y, int index) {
  fill(255);
  float puffSize= (sin(angle+index)*10)+20;
  ellipse(x,y,puffSize,puffSize);
};
 
 
void mouseMoved(){
  currentPuff++;
  if (currentPuff >= puffsX.length) {
    currentPuff = 0;
  }
  puffsX[currentPuff] = mouseX;
  puffsY[currentPuff] = mouseY;
};