© Adam L. Davis 2020
A. L. DavisModern Programming Made Easyhttps://doi.org/10.1007/978-1-4842-5569-8_5

5. Arrays, Lists, Sets, and Maps

Adam L. Davis1 
(1)
Oviedo, FL, USA
 

So far, I’ve only talked about single values, but in programming, you often have to work with large collections of values. For this, we have many data structures that are built into the language. These are similar for Java, Groovy, Scala, and even JavaScript.

Arrays

An array is a fixed size collection of data values.

You declare an array type in Java by appending [] to the type. For example, an array of ints is defined as int[].
1   int[] vampireAges = new  int[10]; // ten vampires
Setting and accessing the values in an array uses the same square bracket syntax, such as the following:
1   vampireAges[0] = 1565; // set age of first vampire
2    int age = vampireAges[0]  // get age of 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.

../images/435475_2_En_5_Chapter/435475_2_En_5_Figa_HTML.jpg Patient 0 Here’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 = 2020; // 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. For example, the following would declare an array of Vampire objects:
1   Vampire[] vampires = new Vampire[10]; // Vampire array with length 10
You can also populate your array directly, such as if you’re creating an array of strings, for example.
1   String[] names = {"Dracula", "Edward"};

The Array object in JavaScript is more like a Java List. Java arrays are a somewhat low-level structure used only for performance reasons. In Groovy 3, the Java-style declaration of arrays is supported. In previous versions you would have to use the List style, which we cover next.

In Scala, you can define an Array like one of the following:
1   var names = new Array[String](2) // size of 2 without values
2   var names = Array("Dracula", "Edward") // size of 2 with values

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 List, a re-sizable collection of ordered elements.

In Java, you create List<E> in the following way:
1   List<Vampire> vampires = new ArrayList<>();

The class between the first angle brackets (<>) defines the generic type of the list—what can go into the list (in this case it is Vampire). The second set of angle brackets can be empty since Java can infer the generic type from the left side of the expression. You can now add vampires to this list all day, and it will expand, as necessary in the background.

You add to 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 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 List is empty

  • clear(): Removes all values from List

    ../images/435475_2_En_5_Chapter/435475_2_En_5_Figb_HTML.jpg In Java, List is an interface (we’ll cover interfaces in depth in Chapter 8) and has many different implementations, but here are two:

  • java.util.ArrayList

  • java.util.LinkedList

    The only difference you should care about is that, in general, LinkedList grows faster when inserting a value at an arbitrary index, while ArrayList’s get() method is faster at an arbitrary index.

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 (it reuses the existing list in the background for performance reasons). This is because the default List in Scala is immutable, meaning it cannot be modified (the default implementation is immutable, but you can use a mutable implementation from the scala.collection.mutable package). Although this may seem strange, in conjunction with functional programming, it makes parallel programming (programming for multiple processors) easier as we’ll see in Chapter 10.

JavaScript Arrays

As mentioned earlier, JavaScript uses Array1 instead of List. Also, since JavaScript is not strictly typed, an Array can always hold objects of any type.

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 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

Sets

Set<E> is much like List<E>, but each value or object can only have one instance in the Set , whereas in previous collections, there can be repeats.

Set has many of the same methods as List. However, it is missing the methods that use an index, because 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
Note

To preserve insertion order, you can use a LinkedHashSet<E> which uses a doubly linked list to store the order of the elements in addition to a hash table to preserve uniqueness.

In Java, there is such a thing as SortedSet<E>, which is implemented by TreeSet<E>. For example, let’s say you wanted a sorted list of names, as follows:
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]

TreeSet will magically always be sorted in the proper order.

../images/435475_2_En_5_Chapter/435475_2_En_5_Figc_HTML.jpg Okay, it’s not really magic. The object to be sorted must implement the Comparable interface, but you haven’t learned about interfaces yet (interfaces are covered in Chapter 8).

JavaScript does not yet have a built-in Set class. Groovy uses the same classes for Set as Java. Scala has its own implementations of Set. For example, you can define a normal Set or SortedSet in Scala as follows:
1  var nums = Set(1, 2, 3)
2  var sortedNums = SortedSet(1, 3, 2)

Maps

Map<K,V> is a collection of keys associated with values. The K specifies the generic type for keys, and the V specifies the generic type for 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 as for List, Groovy has a simpler syntax for creating and editing Map.
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 and Set, 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 Object2 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"].

Summary

This chapter introduced you to the following concepts:
  • Arrays: Collections of data with a fixed size

  • Lists: An expandable collection of objects or values

  • Sets: An expandable collection of unique objects or values

  • Maps: A dictionary-like collection

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset