5. Arrays, Lists, Sets, and Maps
So far we’ve only talked about single values, but in programming you often need to work with large collections of values. For this we have many data structures which are built in to the language (these are similar for Java, Groovy, Scala, and even JavaScript).
5.1 Arrays
An array is a fixed size collection of data values. Honestly, you probably won’t use an array very often, but it’s an important concept to learn.
You declare an array-type in Java by appending [] to the type.
For example, an array of int’s is defined as int[].
1 int[] vampireAges = new int[10]; // ten vampires
Accessing the values in an array uses the same square-bracket syntax, such as:
1 vampireAges[0] = 1565; // first vampire
As you can see, the first index of an array is zero. Things tend to start at zero when programming; try to remember this.
|
Patient 0Here’s a helpful metaphor: the first person to start an outbreak (a zombie outbreak, for example) is known as patient zero. Not patient one, patient one is the second person infected. |
This also means that the last index of the array is always one less than the size of the array. This is also true for Lists.
1 vampireAges[9] = 442; // last vampire
You can reassign and access array values just like any other variable.
1 int year = 2014; // current year?
2 int firstVampBornYear = year - vampireAges[0];
You can also declare arrays of objects as well. In this case, each element of the array is a reference to an object in memory.
1 Vampire[] vampires = new Vampire[10]; // Vampire array with length 10
You can also populate your array directly; if you’re creating an array of Strings for example:
1 String[] names = {"Dracula", "Edward"};
Unfortunately, arrays are difficult to use in Groovy and the Array object
in JavaScript is more like a Java List.
Java arrays are a somewhat low-level structure only used for performance reasons.
5.2 Lists
Of course, we don’t always know how many elements we need to store in an array. For this reason (and many others), programmers invented the List, a resizable collection of ordered elements.
In Java, you create a List in the following way:
1 List<Vampire> vampires = new ArrayList<>();
The angle-brackets (<>) define the generic type of the list - what can go into the list.
You can now add Vampires to this list all day, and it will expand as necessary in the background.
You add to a List like this:
1 vampires.add(new Vampire("Count Dracula", 1897));
List also contains tons of other useful methods, including:
-
size()- Gets the size of the List. -
get(int index)- Gets the value at that index. -
remove(int index)- Removes the value at that index. -
remove(Object o)- Removes the given object. -
isEmpty()- Returns true only if the List is empty. -
clear()- Removes all values from the List.
|
In Java,
The only difference you care about is that, in general, LinkedList grows faster, while ArrayList’s |
You’ll learn how to loop through lists, arrays, and sets (and what “loop” means) in the next chapter.
For now, just know that Lists are a fundamental concept in programming.
Groovy Lists
Groovy has a simpler syntax for creating lists, which is built into the language.
1 def list = []
2 list.add(new Vampire("Count Dracula", 1897))
3 // or
4 list << new Vampire("Count Dracula", 1897)
Scala Lists
In Scala you create a list and add to a List in a slightly different way:
1 var list = List[Vampire]();
2 list :+ new Vampire("Count Dracula", 1897)
Also, this actually creates a new list instead of modifying the existing list. The is because the default List in Scala is immutable meaning it cannot be modified. Although this may seem strange - in conjunction with functional programming - it makes parallel programming (programming for multiple processors) easier.
JavaScript Arrays
As mentioned earlier, JavaScript has the Array instead of a List.
Arrays can be created much like Lists in Groovy.
However, the methods available are somewhat different.
For example, push is used instead of add:
1 def array = []
2 array.push(new Vampire("Count Dracula", 1897))
You can also declare the initial values of the Array. For example the following two lines are equivalent:
1 def years = [1666, 1680, 1722]
2 def years = new Array(1666, 1680, 1722)
To add to the confusion, Arrays in JavaScript can be accessed much like Java arrays. For example:
1 def firstYear = years[0]
2 def size = years.length
5.3 Sets
A Set is much like a List, but each value or object can only have one instance in the Set.
The Set has many of the same methods as List. In particular it is missing the methods that use an index, because a Set is not necessarily in any particular order.
1 Set<String> dragons = new HashSet<>();
2 dragons.add("Lambton");
3 dragons.add("Deerhurst");
4 dragons.size(); // 2
5 dragons.remove("Lambton");
6 dragons.size(); // 1
In Java, there is such a thing as a SortedSet which is implemented by TreeSet. For example, let’s say you wanted a sorted list of names:
1 SortedSet<String> dragons = new TreeSet<>();
2 dragons.add("Lambton");
3 dragons.add("Smaug");
4 dragons.add("Deerhurst");
5 dragons.add("Norbert");
6 System.out.println(dragons);
7 // [Deerhurst, Lambton, Norbert, Smaug]
The TreeSet will magically always be sorted in the proper order.
|
Okay, it’s not really magic. The object to be sorted must implement the Comparable interface, but we haven’t learned about interfaces yet. |
JavaScript does not yet have a built-in Set class.
5.4 Maps
A Map is a collection of keys associated with values.
It may be easier to understand with an example:
1 Map<String,String> map = new HashMap<>();
2 map.put("Smaug", "deadly");
3 map.put("Norbert", "cute");
4 map.size(); // 2
5 map.get("Smaug"); // deadly
Map also has the following methods:
- containsKey(Object key) - Returns true if this map contains a mapping for the specified key.
- containsValue(Object value) - Returns true if this map maps one or more keys to the specified value.
- keySet() - Returns a Set view of the keys contained in this map.
- putAll(Map m) - Copies all of the mappings from the specified map to this map.
- remove(Object key) - Removes the mapping for a key from this map if it is present.
Groovy Maps
Just like for Lists, Groovy has a simpler syntax for creating and editing Maps:
1 def map = ["Smaug": "deadly"]
2 map.Norbert = "cute"
3 println(map) // [Smaug:deadly, Norbert:cute]
Scala Maps
Scala’s Map syntax is also somewhat shorter:
1 var map = Map("Smaug" -> "deadly")
2 var map2 = map + ("Norbert" -> "cute")
3 println(map2) // Map(Smaug -> deadly, Norbert -> cute)
As with List above, Scala’s default Map is also immutable.
JavaScript Maps
JavaScript does not yet have a built-in Map class, but it can be approximated by using the built-in Object syntax. For example:
1 def map = {"Smaug": "deadly", "Norbert": "cute"}
You could then use either of the following to access map values: map.Smaug or map["Smaug"].
5.5 Summary
This chapter introduced you to the following concepts:
- Arrays: primitive collections of data.
- Lists: An expandable collection of objects or values.
- Sets: A collection of unique objects or values.
- Maps: A dictionary-like collection.