The labs on this site need JavaScript to run. The same content is written out below.
Fundamentals › Java
List and Map
How do you put values into a List and a Map, and get them out?
Why it exists — An array needs its size decided when it is made, so when more values come, you must write code yourself that makes a bigger array and copies the values over, and to find a value by name you must compare from the start one by one. The List and Map that Java provides (ArrayList, HashMap, and so on) do this work for you: a List appends a value at the end with one line of add, and a Map takes out the paired value directly with one key.
Where it's used today — Values to be lined up in order, such as several members read from a database or the products in a shopping cart, are handled as a List. Values for which what to search by is fixed, such as finding a member by member number or a setting value by setting name, are handled as a Map. Something that must not have the same value twice (a list of IDs already used, and so on) uses a Set.
An object that gathers several values so that you can work with them together is called a collection. A collection object does not hold the values themselves inside it. It has references that point to the values (objects), one after another. A List keeps values in a line, in the order you put them in, and you get them out by an index that starts at 0. A Map keeps keys paired with values, and you get a value out by its key. In code, as in List<String> names = new ArrayList<>();, you write on the left the kind of collection that the variable can refer to (the part in angle brackets is the kind of value you put in), and the new on the right creates an empty list object. You do not write a size in the parentheses. The count (size) grows as you put things in with add or put. In this lab you switch between List and Map, and the same shape of code is compiled and run, and you see what is printed when you get something you put in, when you get something you did not put in, and when you put the same thing in once more. (The count is printed first so that you can see it even when the program stops while getting.)
Checked against real execution · Compiled 6 combinations with javax.tools on JDK 21, ran them as child java processes, and checked the standard output, the standard error, and the exit code
Concepts in this lab
- List, Set, Map
- These are the three basic kinds of Java collections. A List is ordered, allows duplicates, and is accessed by index. A Set does not allow duplicates. A Map stores key-value pairs, and its keys cannot be duplicated. You choose among them by the nature of the data (whether order is needed, whether duplicates are allowed, and whether you look things up by key).
- List add() and get()
- Why it exists — When you put values in an array, you have to decide which index each one goes into, so you have to keep a separate count of how many you have added so far. With a List, add() only attaches a value to the end, and the List counts the values by itself.
- Where it's used today — Use add() to add products to a shopping cart one by one, and get() to take out a value whose position is fixed, such as the first product. To go through all of them in order, a for loop that runs without an index, as in for (String s : list), is commonly used.
- A List is an object that keeps several values in a line, in the order you put them in. It has references that point to the values (objects), one after another, and each value is identified by an integer index that starts at 0. add(value) attaches the value to the end of the List, and get(index) returns the value at that index. The same value can be put into a List several times, so adding the same value again makes one more slot at a different index. size() returns the number of values the List has, and the indexes you can use are 0 up to size() - 1. ArrayList is a class built by the rules of List. It grows the array it uses by itself as you add values, so you do not have to decide a size when you create it.
- Map put() and get()
- Why it exists — To pair names with values without a Map, you have to put them in two Lists separately and match them by the same index, so if you delete from only one of them, the pairs go out of step. A Map's put() pairs a key with a value in one step, and get() returns the paired value when you give only the key.
- Where it's used today — Use it for values that are looked up by something fixed, such as finding a price by product code or counting how many times each word appears. To count, take the current value with getOrDefault(word, 0), add 1, and put it again under the same key.
- A Map is an object that keeps keys paired with values (it has references that point to the keys and the values, in pairs), and you get a value out by its key, not by an index. One Map cannot have two of the same key, and one key is paired with one value. put(key, value) pairs a key with a value, and if that key is already there, it does not create a new pair but replaces the old value with the new one and returns the old value. get(key) returns the value paired with that key, and returns null without an exception if there is no paired value. In a Map that also allows null as a value, get returning null may not mean that the key is absent, and you check whether the key exists separately with containsKey. HashMap is a class built by the rules of Map, and it does not guarantee the order in which things come out.
- IndexOutOfBoundsException
- Why it exists — In a language like C, an index outside an array is not checked, so you can read or change unrelated memory, and the mistake often shows up much later in another place. Java checks the range every time an index is used, and when it is out of range, it throws this kind of exception right on that line.
- Where it's used today — If the error output shows a message such as Index 3 out of bounds for length 3, first check whether the loop condition was written as i <= size() instead of i < size(), so that it ran one time too many.
- IndexOutOfBoundsException is the exception that is thrown when you refer to something by an index, such as an array, a string, or a List, and the index is out of range. The get(index) of a List throws this exception if the index is less than 0 or greater than or equal to size(). It is a subclass of RuntimeException. Code with a wrong index still compiles, and the exception is thrown when that line runs.
Try these
- Default settings — Index 0 refers to "kim" and index 1 to "lee", and get(0) gets "kim".
- Getting an index that is not in the List — The only indexes are 0 and 1, so an exception is thrown and the program stops.
- Putting the same value in the List again — It does not stop you. It puts in one more, and the count becomes 3.
- Switching to Map and getting by key — It gets the value 20 that was paired with the key "kim".
- Getting a key that is not in the Map — No exception is thrown, and null comes out.
- Putting the same key in the Map again — No new pair is created. Only the value changes to 25.
Running with the default settings
- You run it with java Main. The first line of main, List<String> names = new ArrayList<>();, runs. The List<String> on the left means "a List that has references to String objects," and it decides what kind of object the variable names can refer to. The new ArrayList<>() on the right creates an empty List object with nothing put in it, and names refers to that object (what names stores is a reference that points to the object, not the object itself). List is the name of the rules for putting values in and getting them out, and ArrayList is a real class built by those rules. No size is written in the parentheses. The number of values it has is 0.
- The line names.add("kim"); runs. add attaches a value to the end of the List. It was empty, so "kim" goes in at index 0. Indexes start at 0 and are numbered in the order you put values in. The number of values it has is 1.
- The line names.add("lee"); runs. add attaches a value to the end of the List. "lee" goes in at index 1, right after "kim". The number of values it has is 2.
- The line System.out.println(names.size()); prints the number of values the List has. The number printed is 2.
- At the line System.out.println(names.get(0));, the call get(0) returns the value at index 0, and println prints "kim". The index to get is the 0 written in the parentheses. Getting a value does not remove it from the List, so the number of values it has stays 2.
- The last line of main runs and the program ends.
Result of this run
- A List keeps values in a line, in the order you put them in, and you get them out by an index that starts at 0. add put "kim" and "lee" at indexes 0 and 1, and the call get(0) got "kim".
- No size was written in the parentheses of new ArrayList<>(), yet the count grew as much as you put in. An array has its length decided when it is created and never changes after that (section 10.2 of the Java Language Specification), but a List grows as you put values in. The values stay in the List after you get them.
Code
// Import java.util, which contains the collection classes
import java.util.*;
public class Main {
public static void main(String[] args) {
// List: a collection that keeps values in a line, in the order you put them in. It starts out empty
List<String> names = new ArrayList<>();
// Put in: add attaches the value to the end. Indexes are numbered from 0
names.add("kim");
names.add("lee");
// Count: size returns the number of values the list has
System.out.println(names.size());
// Get: get returns the value at that index
System.out.println(names.get(0));
}
}
Assumptions of this model
The compiler and runtime are JDK 21.0.12.1 (javac 21). All 6 combinations were checked against real runs: the same source as the code on the screen (identical line by line) was compiled with javax.tools and all of them compiled, and the compiled Main was run by starting the java of this JDK as a child process, and the standard output, the standard error, and the exit code were captured. What was checked is whether compilation succeeded, the lines of the standard output (the count and the value retrieved), and the exit code and the first line of the standard error (the combination that throws an exception had exit code 1 and the first line Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 5 out of bounds for length 2, followed by a stack trace with Main.main in the standard error, and the others had exit code 0 and an empty standard error). The facts that the step sentences rely on were checked by running separate source in the same way. In the List, "kim" and "lee" go in at indexes 0 and 1 (the indexOf results were 0 and 1), the count stays 2 after a get, and putting the same "kim" in again makes a separate slot at index 2 (get(2) was kim, and the count was 3). In the Map, calling put with the same key returns the old value 20 and the value becomes 25 with the pairs staying at 2, and for the key park, which was not put in, get is null and containsKey is false. For the documentation, I opened the Java SE 21 API documentation myself. That indexes in a List start at 0 and that the same value can be put into a List several times, that add attaches to the end, and that get throws an IndexOutOfBoundsException for an index out of range follow java.util.List and java.util.ArrayList; that an ArrayList grows its capacity by itself as you add follows java.util.ArrayList; that a Map cannot have two of the same key, that get returns null when there is no pair, and that put replaces the old value and returns it follow java.util.Map and java.util.HashMap; that IndexOutOfBoundsException is a subclass of RuntimeException follows java.lang.IndexOutOfBoundsException; and that the length of an array does not change after it is created follows section 10.2 of the Java Language Specification (Java SE 21). I opened these documents in a way that returned summaries of their content, so I did not read every word of the original text myself. That the code compiles even with a wrong index and that the exception is thrown at run time, and the exit code 1 and the text in the standard error, were not taken from the documentation but observed with this java. The code on the screen has exactly the shape that is run with java Main, and there is no package. The count is printed first and the line that gets comes after it so that, even in the combination that stops while getting, the count can be checked in the output. The dashed slots in the diagram (index 5, key park) are drawn to point to a position that does not exist, and they do not mean that a real List or Map has such a slot. Other methods of List and Map (remove, contains, and so on), ways to go through all the items, Set, how the order of retrieval is decided, and putting null in as a value are not covered. The difference between ArrayList and LinkedList is covered in the in-depth lab "ArrayList and LinkedList", how HashMap finds a key in "Inside HashMap", and the order of the kinds of Set and Map in "Kinds of Set and Map".
Previous lab: Generics · Next lab: Lambdas