Presentation is loading. Please wait.

Presentation is loading. Please wait.

The List Interface and ArrayLists

Similar presentations


Presentation on theme: "The List Interface and ArrayLists"— Presentation transcript:

1 The List Interface and ArrayLists
Section 12.1

2 Outcomes Use a List in place of an Array
create an ArrayList or a LinkedList add, get, change, and remove elements loop thru it using for and for-each loops Loop thru a List using a ListIterator add and remove elements as you loop Recognize other kinds of Collections Use Collections class methods

3 Lists are for Listing Things
What do you want to do with a list? add stuff to it print it out look to see what’s on it check how long it is check if some particular thing’s on it remove stuff from it List interface has methods for all those and lots more!

4 List ADT and Interface What is a list?
sequence of things, all the same type (1st item, 2nd item, 3rd item, ..., last item) java.util.List interface is parameterized say what kind of objects are allowed on it list of Strings: List<String> myWords; list of Files: List<File> myFiles; list of integers: List<Integer> myNumbers; NOTE: List<int> is not allowed

5 List Data Types List is an interface Two kinds of List objects
OK for variables List<String> var; but not for objects var = new List<String>(); Two kinds of List objects ArrayList var = new ArrayList<String>(); LinkedList var = new LinkedList<String>(); used exactly the same way! choose depending on what needs doing both from java.util

6 Side-by-Side List<String> list; list = new ArrayList<String>(); list.add("ten"); list.add("twenty"); list.add("thirty"); System.out.println(list); list.remove("twenty"); List<String> list; list = new LinkedList<String>(); list.add("ten"); list.add("twenty"); list.add("thirty"); System.out.println(list); list.remove("twenty"); [ten, twenty, thirty] [ten, thirty] [ten, twenty, thirty] [ten, thirty]

7 Creating a List and Adding to it
Normal variable + new object declaration List<String> myWords = new ArrayList<String>(); 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

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 directly!
System.out (to screen) or a PrintWriter (to file) System.out.println("The list is " + myWords + "."); Output just like Arrays.toString(…) elements printed using their toString method 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 Where exactly is it? indexOf if (myWords.contains("Twenty")) { System.out.println("We have a Twenty!"); System.out.println("It’s at location " + myWords.indexOf("Twenty") + "."); } We have a Twenty! It’s at location 2.

13 Looking for Particular Items
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! It’s at location 2. 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 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) They 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!

16 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

17 Simplified for Loop for (String word : allMyWords) { System.out.println("\t" + word); } "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords Ten Fifteen Twenty Thirty Fifty

18 Exercise Write a code fragment that reads a single line of words and adds them all to a List, then prints out the list Enter a line of words below: This is the line of words I entered. The words you entered were: [This, is, the, line, of, words, I, entered.]

19 Exercise Make this program using Lists N heats; top 2 advance
What order did they finish in heat 1? Jill Anne Leslie Freida What order did they finish in heat 2? Carol Louisa Judith Annette What order did they finish in heat 3? Carla Giselle Lois Rachel What order did they finish in heat 4? Yvonne Darla Brenda The people who advanced are: [Jill, Anne, Carol, Louisa, Carla, Giselle, Yvonne, Darla] Not advancing were: [Leslie, Freida, Judith, Annette, Lois, Rachel, Brenda]

20 List Iterators To add or remove items while looping
List Iterator goes thru list one item at a time like a Scanner going thru a file: next and hasNext 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

21 Creating a List Iterator
Parameterized, just like List & ArrayList just ask the list for one ListIterator<String> it = allMyWords.listIterator(); no “new ListIterator<String>()” type needs to be the same as the List’s type "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords & it

22 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

23 Removing with an Iterator
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

24 ListIterators Can Go in Reverse
Start at the last element use previous & hasPrevious public static void writeListReversed(List<String> list) { ListIterator<String> it = list.listIterator(list.size()); while(it.hasPrevious()) { System.out.println("\t" + it.previous()) } not as clumsy as the for loop version

25 Removing with an Iterator
Going backwards is the same! while (it.hasPrevious()) { String word = it.previous(); if (word.startsWith("F")) it.remove(); } "Fifteen" word "Ten" word "Twenty" word "Fifty" word "Thirty" word "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords & it

26 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

27 Changing with an Iterator
Same as removing but we’re just changing instead of removing 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

28 Changing with an Iterator
Change words starting with F to upper case! while (it.hasPrevious()) { String word = it.previous(); if (word.startsWith("F")) it.set(word.toUpperCase()); } "Fifty" word "Thirty" word "Ten" word "Fifteen" word "Twenty" word "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords "FIFTEEN", "FIFTY" & it

29 Adding with an Iterator
Adds towards the front of the list if going forward, then iterator will not see them if going backward. iterator will see them "Ten", "A", "Fifteen", "Twenty", "Thirty", "Fifty" "Ten", "A", "B", "Fifteen", "Twenty", "Thirty", "Fifty" "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" & it "Ten", "Fifteen", "Twenty", "Thirty", "A", "Fifty" "Ten", "Fifteen", "Twenty", "Thirty", "B", "A", "Fifty" "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" & it

30 Exercise Use an iterator to go thru a List<Integer>, removing every negative number and changing every 0 to a 42 go from front to back How would it change if we wanted to go from back to front?

31 List Interface More List interface methods
isEmpty() check if list is empty clear() make list empty addAll(otherList) add all these containsAll(otherList) check if contains these removeAll(otherList) remove all these retainAll(otherList) keep only these subList(from, to) get part of the list

32 Check if a List is Empty Can use myList.size() == 0…
but this is a bit easier and clearer S.o.p("List is now " + myList); if (myList.isEmpty()) S.o.p("My list is empty"); else S.o.p("My list isn’t empty"); List is now [Ten, Fifteen, Twenty, Thirty, Fifty] My list isn’t empty

33 Clear a List Make this list empty again
removes every element from the list if (myList.isEmpty()) S.o.p("My list is empty"); else S.o.p("My list isn’t empty"); myList.clear(); if (myList.isEmpty()) S.o.p("Now my list is empty"); else S.o.p("My list still isn’t empty"); My list isn’t empty Now my list is empty

34 Add Elements from Another List
For adding many elements at once combine two lists S.o.p("Section A: " + sectionA); S.o.p("Section B: " + sectionB); List<String> combined = new ArrayList<String>(); combined.addAll(sectionA); combined.addAll(sectionB); S.o.p("Combined: " + combined); Section A: [Bill, Carol, Laura] Section B: [Ann, Don, Ed, Fran] Combined: [Bill, Carol, Laura, Ann, Don, Ed, Fran]

35 Check for Several Elements
Are these all there or not? S.o.p("Combined: " + combined); if (combined.containsAll(sectionA)) S.o.p("All section A’s in the combined list"); if (sectionA.containsAll(combined)) S.o.p("Everyone from the combined list is in section A"); else S.o.p("Someone in the combined list is not in section A"); Combined: [Bill, Carol, Laura, Ann, Don, Ed, Fran] All section A’s in the combined list Someone from the combined list is not in section A

36 Remove Multiple Elements
Take these away, if they’re there no problem if they’re not there S.o.p("Combined: " + combined); sectionA.add("Gil"); S.o.p ("Section A: " + sectionA); combined.removeAll(sectionA); S.o.p ("Combined: " + combined); Combined: [Bill, Carol, Laura, Ann, Don, Ed, Fran] Section A: [Bill, Carol, Laura, Gil] Combined: [Ann, Don, Ed, Fran]

37 Retain Multiple Elements
Keep only these, if they’re there no problem if they’re not there S.o.p("Combined: " + combined); List<String> keepers = new LinkedList<String>(); keepers.add("Ann"); keepers.add("Bill"); keepers.add("Louise"); keepers.add("Ed"); combined.retainAll(keepers); S.o.p ("Combined: " + combined); Combined: [Ann, Don, Ed, Fran] Combined: [Ann, Ed]

38 Getting Parts of Lists Choose first element of list (by position), and first element not on the list (by position) List<String> letters = new ArrayList<String>(); letters.add("b"); letters.add("i"); letters.add("e"); letters.add("y"); letters.add("o"); S.o.p("Letters: " + letters); S.o.p("Letters 1 to 3:" + letters.subList(1, 3)); Letters: [b, i, e, y, o] Letters 1 to 3: [i, e]

39 Sublists Actually part of the larger list (not a copy)
Select part of the list [b, i, e, y, o] letters.subList(1, 3)  [i, e] Actually part of the larger list (not a copy) can be used to modify parts of the list letters.subList(1, 3).set(1, "x"); [b, i, x, y, o] letters.subList(1, 3).clear(); [b, y, o] b i e y o 1 2 3 4 5 1 2 b i e x y o 1 2 3 4 5

40 Exercise Recall the race program from last time Add drugs testing:
several heats, top 2 runners advance Add drugs testing: get a list of runners failing their drug tests disqualify them from advancing what method do we use?

41 the Collection interface
List interface extends Collection interface Collection is an object that holds other objects Collections have base types (<String>, ...) Sets are another kind of Collection as are Queues Collection<E> List<E> Set<E> Queue<E> Collection, List, Set & Queue are interfaces; ArrayList & LinkedList are classes ArrayList<E> LinkedList<E>

42 Collection Methods Common to Lists, Sets and Queues
add(T), remove(T), clear() contains, equals, isEmpty, size, toArray addAll, containsAll, removeAll, retainAll hashCode, iterator List and Deque add several methods different methods for each Set adds no more methods

43 Lists vs. Sets List elements allow duplicates; Sets do not
list1 [a, b, c, a, b, d, a, a, a, a, b, z] set1 [a, b, c, d, z] Client puts List elements in order; computer chooses order for Set elements list1.add("e"); [a, b, c, a, b, d, a, a, a, a, b, z, e] set1.add("e"); [a, b, c, d, e, z] Set interface implemented by (e.g.) TreeSet

44 the Collections class the Collections (note the s) class has several static methods for working with Collection objects (like ArrayLists) Collection is an interface implemented by class such as ArrayList Collections is a class has methods that are useful for Collection objects (such as an ArrayList)

45 Sorting Lists You can write your own sorting method...
using insertion sort, merge sort, quick sort, ... ...or you can use sort from Collections import java.util.Collections; ... Collections.sort(words); sorts into lexicographic order

46 Sorting into Alphabetical Order
sort can be told to use a different order for example, to ignore case Collections.sort(words, String.CASE_INSENSITIVE_ORDER); the list to sort comes first, the comparator next a comparator is an object that lets you compare two other objects – in this case Strings you can create your own comparators by implementing the Comparator interface

47 Other Collections Methods
Collections.methodName(args..); frequency(list, 10)  2 [10, 20, 10, 5] max(list)  20 [10, 20, 10, 5] min(list)  5 [10, 20, 10, 5] reverse(list) [5, 10, 20, 10] replaceAll(list, 10, 7) [5, 7, 20, 7] swap(list, 0, 2) [20, 7, 5, 7] shuffle(list) maybe [7, 20, 5, 7] max & min can also take comparators as 2nd argument

48 Exercise Write a method that shows how many of each element is in a List<Integer> – but only in the range of the elements in the list for example: [10, 5, 10, 3, 5, 10, 22, 19, 10, 5] 3 appears 1 time(s) 4 appears 0 time(s) 5 appears 3 time(s) ... 22 appears 1 time(s)

49 Questions


Download ppt "The List Interface and ArrayLists"

Similar presentations


Ads by Google