Presentation is loading. Please wait.

Presentation is loading. Please wait.

ArrayLists, LinkedLists, Collections Section 12.1.

Similar presentations


Presentation on theme: "ArrayLists, LinkedLists, Collections Section 12.1."— Presentation transcript:

1 ArrayLists, LinkedLists, Collections Section 12.1

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?  sequence of things, all the same type  (1 st item, 2 nd item, 3 rd 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  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  Normal variable + new object declaration ArrayList 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” myWords "Ten" myWords "Ten", "Twenty" myWords "Ten", "Fifteen", "Twenty" myWords

7 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  not like array objects »array has a length when you create it »that’s its length as long as it exists

8 Compiler Warnings  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  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 + “.”);  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 + “.”); The list is [Ten, Fifteen, Twenty]. The first word is Ten. "Ten", "Fifteen", "Twenty" myWords "Ten" firstWord

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) + “.”); 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  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  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  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  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(); 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?  ArrayLists 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 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, ArrayList,...  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(); 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 Exercise  Revise this code to read integer values instead of doubles Scanner kbd = new Scanner(System.in); ArrayList myNumbers = new ArrayList (); double x = kbd.nextDouble(); while (x > 0) { myNumbers.add(x); x = kbd.nextDouble(); myNumbers.add(x); x = kbd.nextDouble();}

25 Important Reminder!  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!)  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 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” allMyWords & it Ten Fifteen Twenty Thirty Fifty

29 next and hasNext  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

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();} “Ten”, “Fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords & it “Ten” word “Fifteen” word “Twenty” word “Thirty” word “Fifty” word

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”, “Fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords & it “FIFTEEN”, “FIFTY” “Ten” word “Fifteen” word “Twenty” word “Thirty” word “Fifty” word

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());} “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

36 Exercise  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?

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 nums = new LinkedList (); for (int n = 1; n <= MAX; ++n) { nums.add(n); }  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.

40 Other Collections  Collection: you can add other objects to it  ArrayList, LinkedList, Set, Priority Queue, … »a list is a collection with an order (1 st to last)  A set is a collection in no particular order  also does not allow duplicates »java.util.HashSet, java.util.TreeSet,...  A priority queue sorts by importance  most important element removed first »for example, patients in an emergency room

41 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);

42 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]

43 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!

44 Questions?  Next Week  Tuesday: review for first test  Thursday: first test »arrays »methods »objects »arrays in objects »arrays of objects »ArrayLists and Collections


Download ppt "ArrayLists, LinkedLists, Collections Section 12.1."

Similar presentations


Ads by Google