|
1 | | -# About |
| 1 | +# About Lists |
2 | 2 |
|
3 | | -TODO: add information on lists concept |
| 3 | +**Lists** are the ordered sequence collection in Java. |
| 4 | +Unlike arrays, a [`List`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html) can grow in size to accomodate any number of items. |
| 5 | +One standard implementation is the `ArrayList` which is backed by a re-sizable array. |
| 6 | +Another standard implementation is the `LinkedList` class which is backed by a doubly-linked list. |
| 7 | + |
| 8 | +`List`s may be empty or hold any number of items (including duplicates). |
| 9 | +`List`s are a **generic interface** typed to indicate which type of objects they can contain. |
| 10 | +For example: |
| 11 | + |
| 12 | +```java |
| 13 | +List<String> emptyListOfStrings = List.of(); |
| 14 | +List<Integer> singleInteger = List.of(1); |
| 15 | +List<Boolean> threeBooleans = List.of(true, false, true); |
| 16 | +List<Object> listWithMulitipleTypes = List.of("hello", 1, true); |
| 17 | +``` |
| 18 | + |
| 19 | +`List`s have various helpful methods to add, remove, get, and check for an element to be present: |
| 20 | + |
| 21 | +```java |
| 22 | +List<Character> vowels = new ArrayList<>(List.of('a', 'e', 'i', 'o', 'i', 'e', 'a')); |
| 23 | +int startingSize = vowels.size(); // 7 |
| 24 | +vowels.add('u'); // vowels is now ['a', 'e', 'i', 'o', 'i', 'e', 'a', 'u'] |
| 25 | +char a = vowels.get(0); // 'a' |
| 26 | +boolean hadI = vowels.remove('i'); // true and vowels is now ['a', 'e', 'o', 'i', 'e', 'a', 'u'] |
| 27 | +boolean hasI = vowels.contains('i'); // true (still have one more left) |
| 28 | +``` |
| 29 | + |
| 30 | +The [`Collections`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collections.html) class also has some helpful utilities for dealing with collections like `List`: |
| 31 | + |
| 32 | +```java |
| 33 | +List<Integer> numbers = new ArrayList<>(List.of(1, 5, 3, 2, 4)); |
| 34 | +Collections.sort(numbers); // [1, 2, 3, 4, 5] |
| 35 | +Collections.reverse(numbers); // [5, 4, 3, 2, 1] |
| 36 | +Collections.fill(numbers, 42); // [42, 42, 42, 42, 42] |
| 37 | +List<Integer> fiveNines = Collections.nCopies(5, 9); // [9, 9, 9, 9, 9] |
| 38 | +``` |
0 commit comments