What Arrays Solve

Arrays keep many values of one type under one name, with fast access to any item by its index.

Apprentice · Java · Updated

By

As we previously learned, arrays are a fundamental data structure in programming used to store collections of elements. Here are some key reasons why arrays are commonly used.

Efficient Storage and Access

Arrays provide a way to store multiple elements of the same type in a contiguous block of memory. This makes accessing elements by their index very efficient, as it takes the same amount of time to access any element in the array by position. This is true whether you want access to item 10 or 10,000.

Organization and Management

Arrays help organize and manage data efficiently. They allow you to store a collection of related data under a single variable name, making it easier to handle large amounts of data systematically.

Iteration and Manipulation

Arrays support easy iteration over elements, which is useful for performing operations on each element, such as searching, sorting, and modifying data. Many algorithms are designed to work efficiently with arrays due to their predictable structure.

Do it: count the big crowds

The stadium keeps one number for each home game: how many people came. The ticket office wants to know how many games drew a big crowd.

The method gets two values:

  • attendance: an int[], how many people came to each game.
  • bigCrowd: an int, the smallest crowd that counts as big.

For example, four games, with 60000 as a big crowd:

int[] attendance = { 41000, 92746, 65300, 88000 };
int bigCrowd = 60000;
Game People 60000 or more?
1st 41000 no
2nd 92746 yes
3rd 65300 yes
4th 88000 yes
Big crowds 3

So countBigCrowds(attendance, 60000) returns 3.

Your job: write the method countBigCrowds(int[] attendance, int bigCrowd) so it returns, as an int, how many games had a big crowd.

  • A game counts when its crowd is bigCrowd or more. A crowd of exactly bigCrowd counts.
  • If no game had a big crowd, return 0.
  • An empty array has no games, so it returns 0 too.

The method sits in the file, Main.java, with nothing around it: since Java 25, a small program can be written this way, without the public class and static that the lessons' code has.

Practiced live on the lesson page: write the Java right there and check it.

Cheat sheets