Arrays & Arraylists - tstorrnetnz/teaching2022 GitHub Wiki

How to think like a computer scientist (HTTLACS)

Otago Workbook L2

Otago Workbook L3

Learning Aims - understand and use Arrays and Arraylists

This covers what we loosely call collections. In Level 2 you may have been familiar with lists, for example a list of names. Java has multiple ways of doing this that can be chosen depending upon their use. The reading/ relevant parts in our resources are:

  • Chapter 7 of the Y12 Otago uni Level 2 book - Arrays
  • Chapter 3 of the Y13 Otago uni Level 3 book - Array lists
  • Chapter 7 of the How to think like a computer scientist book - Arrays
  • Sections 13.9, 14.1 for Array lists

Key ideas:

Arrays, Arraylists and Hashmaps are ways we can organise collections of data in Java.

  • Arrays are a 'list' where you have a fixed number of places in the list, determined when you create the list. For example a list of days in the week always has 7 elements (spaces/places). Arrays generally are made to hold one type of data, e.g. String or int, NOT String and int.
  • Arraylists are very similar to arrays except you can add or delete elements - it can grow or reduce in size - once it has been created. Arraylists generally are made to hold one type of data, e.g. String or int, NOT String and int.For example, an arraylist of names of students attending a school would work as the number changes over time.
  • Hashmaps are lists that have a key:value structure e.g. NSN:Student Name and are optimised so that you can search them quickly by the key to find the value.

Videos made by me that outline these ideas include:

Some repls that I use for teaching

For you to do:

Work through the above resources as you feel the need (Reading/videos/repls) and the do the following problems:

Extra work for the enthusiastic

Hashmaps

Hashmaps are a type of data structure that allows you to store information as a pair. For example name:address or NSN number: Name

It is much simpler to use hashmaps for data that naturally occurs in pairs than an array or arraylist.

There are special methods for inserting, deleting and searching hashmaps, and also specialised types of hashmaps.

This video introduces the concept of hashmaps - sometimes called hash tables (the last part on linking is not required at this level) This page has a really simple introduction to hashmaps in Java.

And here is a more detailed page that has an example and documentation on how to use hashmaps.

I have made a simple repl that demonstrates this for NSN numbers and student names. https://repl.it/@trevorstorr/Hashmap-example

Task - copy my repl into one of your own. Use the iterator in the “more detailed page” example to find the value “Trevor Storr” and get the NSN number for that entry - ie find the key for a value.