What is an Array?
- What is an Array?
- How to create an Array?
- Array Operations
- Array Capacity and Length
- Some basic knowledge of Programming in Java
Definition
An Array is a collection of items. The items could be integers, strings, objects, booleans, or anything. The items are stored in neighbouring(contiguous) memory locations. Because they're stored together, checking through the entire collection of items is straightforward.
Creating an Array
On a computer, Arrays can hold up to N items. When you create the Array, you decide the value of N. You also need to specify the type of item going into the Array.
In Java, we use the following code to create an Array to hold up to 15 Pokemon Cards. Note that we've included a simple definition of a PokemonCard for clarity.
// The actual code for creating an Array to hold PokemonCards.
PokemonCard[] myCollection = new PokemonCard[15];
// A simple definition for a PokemonCard.
public class PokemonCard {
public String name;
public PokemonCard(String name) {
this.name = name;
}
}
After running the above code, we now have an Array called myCollection
, with 15
places in it. Each place can hold one PokemonCard. At the start, there are no PokemonCard's in the Array; we'll have to actually put them in.
The Array can only hold up to 15
PokemonCards. If we get a 16th PokemonCard, we'll need to make a new Array. We'll look at how we deal with running out of space, in the next chapter.
Before we move onto actually putting some PokemonCards into the Array, though, one thing you might be wondering is why we'd make an Array with only 15
places. Why not just make it hold 1000000
PokemonCards so that we know for sure we'll always have enough space?
Well, the reason is the same as it is for the physical box of PokemonCards. Do you really want to find a box that could hold 1000000
PokemonCards when you currently only have 15 PokemonCards and, in fact, never expect to own more than 100 of them? Is it even worth getting a box that could hold 100 PokemonCards right now, when you only expect to get a few new ones each year? It will take up a lot more space in your home in the meantime.
It's exactly the same with the Array, where the space in your home is analogous to memory on the computer. If you make an Array with 1000000
spaces, the computer will reserve memory to hold 1000000
PokemonCards, even if you only put 15
PokemonCards into it. That memory can't be used for anything else in the meantime—just like the space in your house that has been taken over by that huge cardboard box!
So, you should always make the Array as small as possible to start with. If you need more space, you can always make a new Array and copy the items from the old Array into the new one.