Download presentation
Presentation is loading. Please wait.
Published byAdam Fowler Modified over 8 years ago
1
ArrayLists, LinkedLists, Collections Section 12.1
2
Outcomes n Create and use an ArrayList add, get, change, and remove elements loop thru it using for and for-each loops n Replace an array with an ArrayList n Loop thru an ArrayList using a ListIterator add and remove elements as you loop n Create and use a LinkedList n Recognize other kinds of Collections
3
Lists n What is a list? sequence of things, all the same type (1 st item, 2 nd item, 3 rd item,..., last item) n 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 n There are better ways....
4
Lists are for Listing Things n 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 n Java has a couple of types for this
5
ArrayLists n Class java.util.ArrayList uses an array but provides methods to make using it easier n ArrayList is a parameterized type say what kind of things are allowed on it base class goes inside base class goes inside »list of Strings:ArrayList myWords; »list of Files:ArrayList myFiles; »list of integers:ArrayList myNumbers; NOTE: ArrayList is not allowed
6
Creating a List and Adding to it n Normal variable + new object declaration ArrayList myWords = new ArrayList (); the list starts out empty n 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” myWords "Ten" myWords "Ten", "Twenty" myWords "Ten", "Fifteen", "Twenty" myWords
7
List Objects Grow n 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) n Will grow as long as you keep adding not like array objects »array has a length when you create it »that’s its length as long as it exists
8
Compiler Warnings n If when you compile you get this warning: then you forgot to put the (or whatever) somewhere ArrayList words = new ArrayList(); find where the mistake is and fix it »recompile with –Xlint:unchecked to see where »or just look/search Note: CompilerWarning.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. JCreator & NetBeans may already compile with Xlint:unchecked
9
Printing Out a List n Lists can be printed the usual way! System.out (to screen) or a PrintWriter (to file) »not like arrays! System.out.println(“The list is ” + myWords + “.”); n 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 n Lists use zero-based indexing just like arrays String firstWord = myWords.get(0); System.out.println(“The first word is ” + firstWord + “.”); The list is [Ten, Fifteen, Twenty]. The first word is Ten. "Ten", "Fifteen", "Twenty" myWords "Ten" firstWord
11
Checking its Length n Method called size instead of length not like arrays int size = myWords.size(); System.out.println(“Last is ” + myWords.get(size-1) + “.”); The list is [Ten, Fifteen, Twenty]. The first word is Ten. Last is Twenty. "Ten", "Fifteen", "Twenty" myWords 3 size
12
Looking for Particular Items n Is it there at all? contains Where exactly is it? indexOf if (myWords.contains(“Twenty”)) { System.out.println(“We have a Twenty!”); } 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 n Is it there at all? contains Where exactly is it? indexOf if (myWords.contains(“Hundred”)) { System.out.println(“We have a Hundred!”); } System.out.println(“The location of the Hundred is ” + myWords.indexOf(“Hundred”) + “.”); We have a Twenty! The Twenty’s location is 2. The location of the Hundred is -1.
14
Removing Stuff n 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”);System.out.println(myWords); [Ten, Twenty] [Twenty]
15
Changing List Elements n 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 n 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) n 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(); 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]); System.out.println(arr[i]);} // create the list ArrayList list = new ArrayList (); // fill in its values for (int i = 0; i < N; i++) { list.add(kbd.next()); 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)); System.out.println(list.get(i));}
20
Why Use Array(List)s? n ArrayLists are better if: don’t know how many elements are needed will be adding/removing list elements n 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... n When reading from a file, you often don’t know how many elements there will be use an ArrayList instead of an array n Loop until file ends, adding elements while (fin.hasNext()) { myWords.add(fin.next());} reads all the words of that file into myWords don’t need to check for filled array
22
“Wrapper” Classes n Can’t use primitive types in an ArrayList ArrayList, ArrayList,... n But every primitive type has a wrapper int Integer double Double char Character boolean Boolean n 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(); 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]); System.out.println(arr[i]);} // create the list ArrayList list = new ArrayList (); // fill in its values for (int i = 0; i < N; i++) { list.add(kbd.nextDouble()); 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)); System.out.println(list.get(i));}
24
Reading All Numbers from a File n Loop until no more numbers remember to use wrapper class ArrayList myNumbers = new ArrayList (); Scanner fin = new Scanner(new File(fileName)); while (fin.hasNextDouble()) { myNumbers.add(fin.nextDouble()); myNumbers.add(fin.nextDouble());}fin.close(); »(still need to catch/declare FileNotFoundException)
25
Exercise n Revise this code to read integer values instead of doubles ArrayList myNumbers = new ArrayList (); Scanner fin = new Scanner(new File(fileName)); while (fin.hasNextDouble()) { myNumbers.add(fin.nextDouble()); myNumbers.add(fin.nextDouble());}fin.close();
26
Important Reminder! n Don’t add/remove el t s 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!) n Use a java.util.ListIterator instead
27
List Iterators n 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 n Can also use it for changing items or just to look at the items
28
Creating a List Iterator n Parameterized, just like ArrayList ask the list for one–so it knows which list to use ListIterator it = allMyWords.listIterator(); »no “new ListIterator ()” type needs to be the same as the List’s type “Ten”, “Fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords & it
29
Looping thru the List n hasNext: is there is another item? n next: get the next item (and advance) while (it.hasNext()) { System.out.println(it.next());} “Ten”, “Fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords & it Ten Fifteen Twenty Thirty Fifty
30
next and hasNext n It’s just next and hasNext NOT nextInt, nextDouble, … even if it’s an ArrayList of Integers or Doubles ArrayList dl = new ArrayList (); ListIterator it = dl.listIterator(); double num = 0; if (it.hasNextDouble()) { num = it.nextDouble(); num = it.nextDouble();} cannot find symbol method hasNextDoublecannot find symbol method nextDouble
31
Removing with an Iterator n Example: Delete items that start with “F” while (it.hasNext()) { String word = it.next(); if (word.startsWith(“F”)) it.remove();} “Ten”, “Fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords & it “Ten” word “Fifteen” word “Twenty” word “Thirty” word “Fifty” word
32
Removing with an Iterator n Which item did you just look at? n That’s the one that gets removed. n 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
33
Changing with an Iterator n Like removing change the item we just looked at n 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
34
Changing with an Iterator n Example: Allcaps items that start with “F” while (it.hasNext()) { String word = it.next(); if (word.startsWith(“F”)) it.set(word.toUpperCase());} “Ten”, “Fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords & it “FIFTEEN”,, “FIFTY” “Ten” word “Fifteen” word “Twenty” word “Thirty” word “Fifty” word
35
Adding with an Iterator n Like removing add where the iterator is “pointing” »new item is “previous” to the iterator n 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
36
Adding with an Iterator n Ex.: Duplicate items that start with “F” while (it.hasNext()) { String word = it.next(); if (word.startsWith(“F”)) it.add(word.toLowerCase());} “Ten”, “Fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords word “Ten” word “Fifteen” word “Twenty” word “Thirty” word “Fifty” word & it “Ten”, “Fifteen”, “fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords “Ten”, “Fifteen”, “fifteen”, “Twenty”, “Thirty”, “Fifty”, “fifty” allMyWords
37
Exercise n Use an iterator to go thru a List, 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?
38
Some Other ArrayList Methods n 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
39
Exercise n 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)?
40
Other Lists n LinkedList is another kind of List use it just like an ArrayList LinkedList words = new LinkedList (); while(fin.hasNext()) { list.add(fin.next()); } does exactly the same things, but... »it’s more efficient at add/remove »it’s less efficient at get/set use whichever one is better for your program »it’s an empirical question! try both ways.
41
Other Collections n Sets sets do not allow duplicates »add a duplicate command ignored computer decides what order to keep them in »usually sorted, but not necessarily! java.util.HashSet, java.util.TreeSet,... use when you only care if it’s there/not-there n Also Deques, Queues
42
The Collections Class n The java.util.Collections class has methods for dealing with Collections import java.util.Collections; n Example: sort your list with this command: Collections.sort(myList); or this one (for alphabetical order) Collections.sort(words, String.CASE_INSENSITIVE_ORDER);
43
Things Collections Can Do n 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]
44
Exercise n If list1 is [50, 19, 21, 44, 18, 21], then what is Collections.max(list1)? 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!
45
Questions? n Next Week review for second test second test »File I/O »Exceptions »ArrayLists
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.