We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I am new to processing and java as well. I've been following some tutorials to generate a bouncy ball sketch.
import java.util.*;
ArrayList balti = new ArrayList();
void setup() {
size(600, 600);
smooth();
for ( int i=0; i<100; i++) {
Aloo keshavball = new Aloo(random(0, width), random(0, 200));
balti.add(keshavball);
}
}
void draw() {
background(0);
for (int i=0; i<100; i++) {
Aloo keshavball = (Aloo) balti.get(i); // I want to focus here !! What is happening here? I am really confused !
keshavball.mainfunction();
}
}
and other file is:
class Aloo {
float x;
float y;
float speedX=random(-5,5);
float speedY=random(-5,5);
Aloo(float _x, float _y) {
x = _x;
y = _y;
}
void mainfunction() {
display();
move();
bounce();
gravity();
}
void display() {
ellipse(x, y, 20, 20);
}
void move() {
x += speedX;
y += speedY;
}
void bounce() {
if (x > width) {
speedX *= -1;
}
if (y > height) {
speedY *= -1;
}
if (x < 0) {
speedX *= -1;
}
if (y < 0) {
speedY *= -1;
}
}
void gravity() {
speedY = speedY +0.25;
}
}
Answers
Good question!
In your question the ArrayList doesn't know which type of objects it holds. Therefore in the line
Aloo keshavball = (Aloo) balti.get(i);
we have to "cast" the object to the typeAloo
.first step:
balti.get(i)
returns an object of an unknown type2nd step:
(Aloo)
"casts" this object to Aloo, which means we tell processing that the unknown object is in fact of type / class Aloo3rd step: with
=
we move this object that now has the type Aloo to an object keshavball of type Alookeshavball is then only temporarily used to start the method mainfunction().
Outdated
This approach is outdated, since nowadays you can tell the ArrayList which type of Objects it holds in the first place, so we don't need to cast anymore.
See
https://www.processing.org/reference/ArrayList.html
Thank you so much Chrisir!
;-)