Download presentation
Presentation is loading. Please wait.
1
ArrayLists, LinkedLists Sets
Lists and Collections ArrayLists, LinkedLists Sets
2
Outcomes Create and use an ArrayList
add, get, change, and remove elements loop thru it using for and for-each loops Replace an array with an ArrayList Loop thru an ArrayList using a ListIterator add and remove elements as you loop Create and use a LinkedList Recognize other kinds of Collections
3
Lists What is a list? We have used arrays for lists
sequence of things, all the same type (1st item, 2nd item, 3rd item, ..., last item) We have used arrays for lists arrays are not ideal for representing lists need to say at start how big it is can’t change its size There are better ways....
4
Lists are for Listing Things
What do you want to do with a list? add values to it print it out look to see what’s on it check how long it is check if some particular value’s on it remove values from it Java has a couple of types for this
5
ArrayLists Class java.util.ArrayList uses an array
but provides methods to make using it easier ArrayList is a parameterized type say what kind of things are allowed on it base class goes inside <angle brackets> list of Strings: ArrayList<String> myWords; list of Files: ArrayList<File> myFiles; list of integers: ArrayList<Integer> myNumbers; NOTE: ArrayList<int> is not allowed
6
Creating a List and Adding to it
Normal variable + new object declaration ArrayList<String> myWords = new ArrayList<>(); the list starts out empty Add method to add items (to end of list) myWords.add("Ten"); myWords.add("Twenty"); can also say where to add to the list myWords.add(1, "Fifteen"); skip over 1 item, then add "Fifteen" "Ten", "Fifteen", "Twenty" myWords "Ten", "Twenty" myWords myWords "Ten" myWords
7
About Creating the List
This is the best way to create the ArrayList ArrayList<String> myWords = new ArrayList<>(); Other ways are allowed… ArrayList<String> myWords = new ArrayList<String>(); ArrayList<String> myWords = new ArrayList(); ArrayList myWords = new ArrayList(); …but please use the best way it’s hard to explain why it’s best for now just trust us
8
List Objects Grow List objects start empty
not like array objects array has a length when you create it array elements are initialized (to 0 if nothing else) Will grow as long as you keep adding that’s its length as long as it exists
9
Printing Out a List Lists can be printed the usual way!
using System.out.println not like arrays! System.out.println("The list is " + myWords + ". "); Output is a single line with brackets and commas elements of list are printed as usual The list is [Ten, Fifteen, Twenty].
10
Getting List Elements Lists use zero-based indexing just like arrays
String firstWord = myWords.get(0); System.out.println("The first word is " + firstWord + "."); "Ten", "Fifteen", "Twenty" myWords "Ten" firstWord The list is [Ten, Fifteen, Twenty]. The first word is Ten.
11
Checking its Length Method called size instead of length
not like arrays int size = myWords.size(); System.out.println("Last is " + myWords.get(size-1) + "."); "Ten", "Fifteen", "Twenty" myWords 3 size The list is [Ten, Fifteen, Twenty]. The first word is Ten. Last is Twenty.
12
Looking for Particular Items
Is it there at all? contains if (myWords.contains("Twenty")) { System.out.println("We have a Twenty!"); } Where exactly is it? indexOf System.out.println("The Twenty’s location is " + myWords.indexOf("Twenty") + "."); We have a Twenty! The Twenty’s location is 2.
13
Looking for Particular Items
Is it there at all? contains if (myWords.contains("Hundred")) { System.out.println("We have a Hundred!"); } Where exactly is it? indexOf System.out.println("The location of the Hundred is " + myWords.indexOf("Hundred") + "."); The location of the Hundred is -1.
14
Removing Stuff What thing to remove, or which position?
int argument remove from that position myWords.remove(1); System.out.println(myWords); object argument remove that object myWords.remove("Ten"); [Ten, Twenty] [Twenty]
15
Changing List Elements
Use the set method to change a value give the location and the new value myWords.set(0, "Thirty"); System.out.println("The list is now " + myWords + "."); The list is now [Thirty].
16
Looping thru a List Multiple ways to loop thru a list
can use the usual for loop for (int i = 0; i < myWords.size(); i++) can use this simplified for loop (for-each loop) for (String word : myWords) These work if you’re just looking at the list can cause trouble if you’re adding or removing from the list at the same time!
17
Usual for Loop for (int i = 0; i < allMyWords.size(); ++i) { System.out.println("\t" + i + ") " + allMyWords.get(i)); } "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords 0) Ten 1) Fifteen 2) Twenty 3) Thirty 4) Fifty
18
Simplified for Loop for (String word : allMyWords) { System.out.println("\t" + word); } "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords Ten Fifteen Twenty Thirty Fifty
19
Arrays vs. ArrayLists // create the array String[] arr = new String[N]; // fill in its values for (int i = 0; i < N; i++) { arr[i] = kbd.next(); } // change a value arr[2] = arr[2] + "!!!"; // print its elements one per line for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); // create the list ArrayList<String> list = new ArrayList<>(); // fill in its values for (int i = 0; i < N; i++) { list.add(kbd.next()); } // change a value list.set(2, list.get(2) + "!!!"); // print its elements one per line for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i));
20
Why Use Array(List)s? ArrayLists are better if: Arrays are better if:
don’t know how many elements are needed will be adding/removing list elements Arrays are better if: you know how many elements you’ll need or a good upper bound you won’t be adding/removing elements except at the end
21
In Particular... When reading data, you often don’t know how many elements there will be user may not know, either! use ArrayList + while instead of array + for ArrayList<String> words = new ArrayList<>(); data = kbd.next(); while (!data.equals(".")) { words.add(data); data = kbd.next(); } int num = kbd.nextInt(); String[] arr = new String[num]; for (int i = 0; i < num; ++i) { arr[i] = data; data = kbd.next(); }
22
“Wrapper” Classes Can’t use primitive types in an ArrayList
ArrayList<int>, ArrayList<double>, ... But every primitive type has a wrapper int Integer double Double char Character boolean Boolean Use the wrapper class instead
23
Arrays vs. ArrayLists (Primitive)
// create the array double[] arr = new double[N]; // fill in its values for (int i = 0; i < N; i++) { arr[i] = kbd.nextDouble(); } // change a value arr[2] = 3.14 * arr[2]; // print its elements one per line for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); // create the list ArrayList<Double> list = new ArrayList<>(); // fill in its values for (int i = 0; i < N; i++) { list.add(kbd.nextDouble()); } // change a value list.set(2, 3.14 * list.get(2)); // print its elements one per line for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i));
24
Exercise Revise this code to read integer values instead of doubles
Scanner kbd = new Scanner(System.in); ArrayList<Double> myNumbers = new ArrayList<>(); double x = kbd.nextDouble(); while (x > 0) { myNumbers.add(x); x = kbd.nextDouble(); }
25
Important Reminder! Don’t add/remove elts in for/foreach loop
you will get some kind of a mistake... see ModificationError.java ...or program will crash see ModificationCrash.java java.util.ConcurrentModificationException (don’t catch this kind of exception!) Use a java.util.ListIterator instead
26
List Iterators To add or remove items while looping
List Iterator goes thru list one item at a time import java.util.ListIterator; like a Scanner going thru a file: next and hasNext while (it.hasNext()) { System.out.println(it.next()); } can remove the item you just looked at can add item beside the one you just looked at Can also use it for changing items or just to look at the items
27
Creating a List Iterator
Parameterized, just like ArrayList ask the list for one–so it knows which list to use ListIterator<String> it = allMyWords.listIterator(); no "new ListIterator<>()" type needs to be the same as the List’s type "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords & it
28
Looping thru the List hasNext: is there is another item?
next: get the next item (and advance) while (it.hasNext()) { System.out.println(it.next()); } Ten Fifteen Twenty Thirty Fifty "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords & it
29
next and hasNext It’s just next and hasNext NOT nextInt, nextDouble, …
even if it’s an ArrayList of Integers or Doubles ArrayList<Double> dl = new ArrayList<>(); ListIterator<Double> it = dl.listIterator(); double num = 0; if (it.hasNextDouble()) { num = it.nextDouble(); } cannot find symbol method hasNextDouble cannot find symbol method nextDouble
30
Removing with an Iterator
Example: Delete items that start with "F" while (it.hasNext()) { String word = it.next(); if (word.startsWith("F")) it.remove(); } "Thirty" word "Fifty" word "Twenty" word "Ten" word "Fifteen" word "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords & it
31
Removing with an Iterator
Which item did you just look at? That’s the one that gets removed. General policy check to see if there is a next/previous save the next/previous into a variable check the variable to see if it needs removed if so, use the iterator’s remove method to remove it
32
Changing with an Iterator
Like removing change the item we just looked at General policy check to see if there is a next/previous save the next/previous into a variable check the variable to see if it needs changed if so, use the iterator’s set method to change it
33
Changing with an Iterator
Example: Allcaps items that start with "F" while (it.hasNext()) { String word = it.next(); if (word.startsWith("F")) it.set(word.toUpperCase()); } "Ten" word "Fifteen" word "Fifty" word "Thirty" word "Twenty" word "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords "FIFTEEN", "FIFTY" & it
34
Adding with an Iterator
Like removing add where the iterator is "pointing" new item is "previous" to the iterator General policy check to see if there is a next/previous save the next/previous into a variable check the variable to see if we need to add if so, use the iterator’s add method to add a new value
35
Adding with an Iterator
Ex.: Duplicate items that start with "F" while (it.hasNext()) { String word = it.next(); if (word.startsWith("F")) it.add(word.toLowerCase()); } "Twenty" word "Fifty" word "Thirty" word "Fifteen" word "Ten" word word "Ten", "Fifteen", "fifteen", "Twenty", "Thirty", "Fifty", "fifty" allMyWords "Ten", "Fifteen", "fifteen", "Twenty", "Thirty", "Fifty" allMyWords "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords & it
36
Exercise Use an iterator to go thru a List<Integer>, removing every negative number and changing every 0 to a 42 do it as two loops: loop #1 removes every negative # loop #2 changes every 0 to a 42 do it as one loop what’s common between the two loops above?
37
Some Other ArrayList Methods
list.methodName(args...); isEmpty() check if list is empty clear() make list empty addAll(otherList) add all these containsAll(otherList) check if has all these removeAll(otherList) remove all these retainAll(otherList) keep only these subList(from, to) get part of the list it doesn’t make a copy; it gives you part of the list
38
Exercise If list1 is [Alex, Betty, Carol, David], and list2 is [Andrew, Betty, Chris], then what is list1 after list1.addAll(list2)? (Same values), after list1.removeAll(list2)? (Same values), after list1.retainAll(list2)? (Same values), after list1.clear()? (Same values), what’s list1.containsAll(list2)? (Same values), what’s list1.subList(2, 4)?
39
Other Lists LinkedList is another kind of List
use it just like an ArrayList LinkedList<Integer> nums = new LinkedList<>(); for (int n = 1; n <= MAX; ++n) { nums.add(n); } Does exactly the same things as ArrayLists with some very small differences Does them in a different way we’ll talk about the differences in CSCI 2341
40
The List Interface ArrayList and LinkedList are both List
List is an interface ArrayList and LinkedList implement it Can replace ArrayList variable with List List<String> words = new ArrayList<>(); List<Double> numbers = new ArrayList<>(); And ArrayList object with LinkedList List<String> words = new LinkedList<>(); List<Double> numbers = new LinkedList<>();
41
Using Lists Should make any variable a List
including (especially) parameters Should make methods return List instead of ArrayList/LinkedList Remember, you can’t create a new List<>() create an ArrayList or LinkedList for now, which one is up to you learn more about choosing in CSCI 2341
42
Other Collections Collection: you can add other objects to it
ArrayList, LinkedList, Set, Priority Queue, … a list is a collection with an order (1st to last) A set is a collection in no particular order also does not allow duplicates A priority queue sorts by importance most important element removed first for example, patients in an emergency room
43
Sets Set is an interface (like List) Do same things in different ways
two common kinds of Sets Set<String> ts = new TreeSet<>(); Set<String> hs = new HashSet<>(); Do same things in different ways for (int i = 1; i <= 4; ++i) { word = kbd.next(); ts.add(word); hs.add(word); } System.out.println(ts); System.out.println(hs); Mark Anthony Young Mark [Anthony, Mark, Young] [Young, Anthony, Mark]
44
The Collections Class java.util.Collections has helpful methods
like java.util.Arrays, but for lists, sets, … import java.util.Collections; Example: sort your list with this command: Collections.sort(myList); or this one (for alphabetical order) Collections.sort(words, String.CASE_INSENSITIVE_ORDER);
45
Things Collections Can Do
Collections.methodName(args..); .max(list) 20 [10, 20, 10, 5, 8] .min(list) 5 [10, 20, 10, 5, 8] .reverse(list) [8, 5, 10, 20, 10] .replaceAll(list, 10, 7) [8, 5, 7, 20, 7] .swap(list, 0, 2) [7, 5, 8, 20, 7] .shuffle(list) maybe [7, 20, 5, 7, 8] which ones of these would work for Sets?
46
Exercise If list1 is [50, 19, 21, 44, 18, 21], then what is Collections.max(list1)? Collections.min(list1)? list1 after Collections.reverse(list1)? list1 after Collections.sort(list1)? list1 after Collections.swap(list1, 1, 3)? list1 after Collections.replaceAll(list1, 0, 21)? careful – it’s a bit of a trick question!
47
Questions?
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.