Presentation is loading. Please wait.

Presentation is loading. Please wait.

ARRAYLIST.. Hazen High School. Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper.

Similar presentations


Presentation on theme: "ARRAYLIST.. Hazen High School. Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper."— Presentation transcript:

1 ARRAYLIST.. Hazen High School

2 Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper Class Boxing Unboxing Comparable Comparison function Natural Ordering

3 What ? Resizable Array [Automatic] Allows Duplication. Order - Maintains Insertion order. Type Safety Capacity and Size

4 Array List The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold

5 Array Lists an ArrayList can dynamically increase or decrease in size. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk

6 Methods and Fields ArrayList list = new ArrayList() Assignment / Insertion list.Add(“Item1”); // Syntax : list.add( ) Size : int arrayListLength = list.Size(); Retrieval : String firstString = list.get(0); // Syntax : list.get( ) Removal : list.Remove(0) // Syntax : list.Remove( ) Others IsEmpty(), Clear(), ToArray(), Set(Index, Object) See full reference list at end of the slide deck.

7 Generics - Type Parameters ArrayList name = new ArrayList (); — When constructing an ArrayList, you must specify the type of elements it will contain between. — This is called a type parameter or a generic class. — Allows the same ArrayList class to store lists of different types. ArrayList names = new ArrayList (); names.add(“Kory Srock”); names.add(“Tod Oney”);

8 Generics Using different classes in Collection. Why ? Better programmability Better Object Orientation Example ArrayList myList = new ArrayList(); ArrayList a = new ArrayList () ArrayList list = new ArrayList ()

9 Array Vs ArrayList Grows automatically Work well with Generics ArrayList stringArrayList = new ArrayList (); Objects vs References Pass by Value --- Pass by Reference

10 ArrayList of primitives? The type you specify when creating an ArrayList must be an object type; it cannot be a primitive type. // illegal -- int cannot be a type parameter ArrayList list = new ArrayList (); But we can still use ArrayList with primitive types by using special classes called wrapper classes in their place. // creates a list of ints ArrayList list = new ArrayList ();

11 Wrapper classes A wrapper is an object whose sole purpose is to hold a primitive value. Once you construct the list, use it with primitives as normal: PrimitiveWrapper intType IntegerType double Double char Character boolean Boolean ArrayList grades = new ArrayList (); grades.add(3.2); grades.add(2.7);... double myGrade = grades.get(0

12 ArrayList versus Array – Code Examples Construction String[] names = new String[5]; ArrayList list = new ArrayList (); Storing a value names[0] = "Michael"; list.add("Michael"); Retrieving a value String s = names[0]; String s = list.get(0);

13 ArrayList vs Array – Code Examples Continued Doing something to each value that starts with "B" for (int i = 0; i < names.length; i++) { if (names[i].startsWith("B")) {... }} for (int i = 0; i < list.size(); i++) { if (list.get(i).startsWith("B")) {... } } Seeing whether the value "Nathaniel" is found for (int i = 0; i < names.length; i++) { if (names[i].equals("Nathaniel")) {... }} if (list.contains("Nathaniel")) {... }

14 Objects storing collections An object can have an array, list, or other collection as a field. public class Course { private double[] grades; private ArrayList studentNames; public Course() { grades = new double[4]; studentNames = new ArrayList ();... } Now each object stores a collection of data inside it. This is called “composition” (the collection is a component)

15 Exercise #1 Write a method addStars that accepts an array list of strings as a parameter and places a * after each element. — Example: if an array list named list initially stores: [the, quick, brown, fox] — Then the call of addStars(list); makes it store: [the, *, quick, *, brown, *, fox, *] Write a method removeStars that accepts an array list of strings, assuming that every other element is a *, and removes the stars (undoing what was done by addStars above).

16 Questions ArrayList list = new ArrayList() list.Add(“Item1”); list.Add(“Item2”); Will this compile ? Yes, assuming declaration of import java.util.ArrayList;

17 Questions.. Cntd.. ArrayList list = new ArrayList() list.Add(“1”); list.Add(“2”); list.Add(3); Will this compile ? Yes, all are added as objects

18 Questions.. Cntd.. ArrayList list = new ArrayList(3) list.Add(“1”); list.Add(“2”); list.Add(“3”); list.Add(“4”); Will this compile ? Yes. ArrayList grows dynamically

19 Questions.. Cntd.. ArrayList list = new ArrayList(4) list.Add(“1”); list.Add(“2”); list.Add(“4”); System.out.println(list.indexOf(“2”)); Will this compile ? Output ? Yes, it will compile Output is 1

20 Questions.. Cntd.. ArrayList list = new ArrayList(4); list.add(“1”); list.add(“2”); list.add(“4”); for(int i=0;i<5;i++) System.out.println(list.get(i)); Will this compile ? Output ? No, IndexOutOfBoundsException What do we need to do to fix it? Change for loop to 4 instead of 5

21 Question.. Tricky ArrayList arr1 = new ArrayList(); ArrayList arr2 = arr1; arr1.Add("Test"); System.out.println(arr1.Length == arr2.Length); Compile? Output ? ArrayList arr1 = new ArrayList(); ArrayList arr2 = new ArrayList(); arr1.Add("Test"); arr2.Add(arr1.get(0)); arr1[0] = “Test1”; System.out.println(arr2.get(0)); Compile? Output ? No, there is no method.length for arraylists, need to use.size What is the output once we change.length to.size? true Won’t compile – arr1[0]= “Test1” is a array type conflict What do we need to do to fix it? Arr1.add(“Test1”)

22 import java.util.*; class ArrayListDemo { public static void main(String args[]) { ArrayList al = new ArrayList(); // create an array list System.out.println("Initial size of al: " + al.size()); // add elements to the array list al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); al.add(1, "A2"); System.out.println("Size of al after additions: " +al.size()); // display the array list System.out.println("Contents of al: " + al); // Remove elements from the array list al.remove("F"); al.remove(2); System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); } Initial size of al: 0 Size of al after additions: 7 Contents of al: [C, A2, A, E, B, D, F] Size of al after deletions: 5 Contents of al: [C, A2, E, B, D] What is the initial size of al? What is the size of al after additions? What is the contents of al? What is the size after deletions?

23 Exercise #2 Use Array List to implement the following exercise Create and Display a List of Employees in a Company with each Employee information containing the following Id Name Date of Birth Designation Address Skill Sets [ Accounts, Sales, Marketing, IT, Support, Management, Delivery ] List of products worked [ ProjectX, PriojectY, ProjectZ, ProjectH ] Each Project should track the list of Employees in it Each Dept./Skill Sets should track the list of Employees in it Hint : Use Static variables to track the List of Employees and Count of them in Project / Department

24 Array List Methods add(value) appends value at end of list add(index, value) inserts given value just before the given index, shifting subsequent values to the clear() right removes all elements of the list indexOf(value) returns first index where given value is found in list (-1 if not found) get(index) returns the value at given index remove(index) removes/returns value at given index, shifting subsequent values to the left set(index, value) replaces value at given index with given size() value returns the number of elements in list toString() returns a string representation of the list such as "[3, 42, -7, 15]"

25 Array List Methods Continued addAll(list) addAll(index, list) adds all elements from the given list to this list (at the end of the list, or inserts them at the given contains(value) index) returns true if given value is found somewhere in containsAll(list) this list returns true if this list contains every element from equals(list) given list returns true if given other list contains the same iterator() listIterator() elements returns an object used to examine the contents of the list (seen later) lastIndexOf(value) returns last index value is found in list (-1 if not remove(value) found) finds and removes the given value from this list removeAll(list) removes any elements found in the given list from retainAll(list) this list removes any elements not found in given list from subList(from, to) this list returns the sub-portion of the list between indexes from (inclusive) and to (exclusive) toArray() returns the elements in this list as an array

26 PracticeIt http://www.garfieldcs.com/2011/02/arraylists-practice/ http://practiceit.cs.washington.edu/problem.jsp?category= University+of+Washington+CSE+143%2FCS2+Exams%2 FCS2+Midterm+Exams%2F143+Practice+Midterm+5&pro blem=143practicemidterm5-ArrayListMystery http://practiceit.cs.washington.edu/problem.jsp?category= University+of+Washington+CSE+143%2FCS2+Exams%2 FCS2+Midterm+Exams%2F143+Practice+Midterm+5&pro blem=143practicemidterm5-ArrayListMystery http://www.garfieldcs.com/2011/03/classes-quiz-practice/

27 Question.. Tricky ArrayList arr1 = new ArrayList(); ArrayList arr2 = arr1.clone(); arr1.Add("Test"); arr2.Add(arr1.get(0)); arr1[0] = “Test1”; System.Out.PrintLn(arr2.get(0)); Output ? ArrayList arr1 = new ArrayList(); ArrayList arr2 = new ArrayList(); arr1.Add("Test"); arr2.Add(arr1.get(0).Clone()); arr1[0] = “Test1”; System.Out.PrintLn(arr2.get(0)); Output ?


Download ppt "ARRAYLIST.. Hazen High School. Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper."

Similar presentations


Ads by Google