Card 01/ 08
All 8 cards
ConceptDifficulty: Beginner1 min
One Name for Twenty Values, and the Number That Picks One
You need the sales total for each of the last seven days. Seven variables called day1 to day7 works until something has to loop over them, and nothing can loop over seven separate names.
An array is one variable holding a fixed run of values of one type, each reachable by its position.
double[] totals = new double[7];
totals[0] = 240.50;
totals[6] = 98.00;Two things are decided the moment that array is created. Its type — double, and nothing else will go in it. And its length — seven, permanently. An array cannot grow, shrink or change type after the line that made it.
| Fixed at creation | Free to change |
|---|---|
| The element type | The value in any slot |
| The number of slots | How many slots you have written to |
So an array is the right shape when you know how many things there will be and they are all alike. The moment the count is not known ahead of time, you want something that can grow — which is what a List is for, and what arrays sit underneath.