简体   繁体   中英

How do I automatically create an array of objects (the number of which is determined by user input)

I am writing a program where I am making a dynamic bar graph which processing reads in from Arduino. From the Arduino side, I have serial input, which I can read from processing and store into an array.

I have created a class for each bar of a bar graph, however I want to make this scalable. If I have 100 bars on the bar graph, is there a way to make 100 different objects automatically?

Yes this is a perfect use for a for loop . In this case:

Object[] array = new Object[100];
for(int i = 0; i < 100; i++){
    array[i] = new Object();
}

You can use an array .

An array is a way of storing multiple instances in one value. So if you have a class named Bar , you can do this:

Bar[] bars = new Bar[100];

This creates an array called bars , which holds 100 indexes. Then you can treat each index as its own variable:

bars[0] = new Bar(42);
bars[1] = new Bar(67);
println(bars[0]);
println(bars[1]);

Where this becomes really useful is when you combine it with a counter or a for loop:

for(int i = 0; i < 100; i++){
   bars[i] = new Bar(whatever);
   println(bars[i]);
}

You can also use an ArrayList which operates on a similar principle but allows you to easily add indexes over time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM