13 December 2021 Review of Previous Lesson State

13 December 2021 Review of Previous Lesson • State as many Vocabulary words and Learning Objectives that you remember from the last lesson as you can. • Remember to grade yourself from 0 - 3. 1

13 December 2021 Object Orientated Programming Paradigm (OOP) Lists & Array. Lists 2

13 December 2021 LEARNING OBJECTIVE Represent collections of related object reference data using Array. List objects. For Array. List objects: a. Traverse using a for or while loop b. Traverse using an enhanced for loop For algorithms in the context of a particular specification that requires the use of Array. List traversals: • Identify standard algorithms. • Modify standard algorithms. • Develop an algorithm. Apply sequential/linear search algorithms to search for specific information in Array. List objects. Apply selection sort and insertion sort algorithms to sort the elements of Array. List objects. 3

13 December 2021 ESSENTIAL KNOWLEDGE An Array. List object is mutable and contains object references. The Array. List constructor Array. List() constructs an empty list. Java allows the generic type Array. List<E>, where the generic type E specifies the type of the elements. When Array. List<E> is specified, the types of the reference parameters and return type when using the methods are type E. Array. List<E> is preferred over Array. List because it allows the compiler to find errors that would otherwise be found at run-time. The Array. List class is part of the java. util package. An import statement can be used to make this class available for use in the program. 4

13 December 2021 ESSENTIAL KNOWLEDGE Iteration statements can be used to access all the elements in an Array. List. This is called traversing the Array. List. Deleting elements during a traversal of an Array. List requires using special techniques to avoid skipping elements. Since the indices for an Array. List start at 0 and end at the number of elements -1, accessing an index value outside of this range will result in an Array. Index. Out. Of. Bounds. Exception being thrown. Changing the size of an Array. List while traversing it using an enhanced for loop can result in a Concurrent. Modification. Exception being thrown. Therefore, when using an enhanced for loop to traverse an Array. List, you should not add or remove elements. 5

13 December 2021 ESSENTIAL KNOWLEDGE There are standard Array. List algorithms that utilize traversals to: • Insert elements • Delete elements • Apply the same standard algorithms that are used with 1 D arrays Some algorithms require multiple String, array, or Array. List objects to be traversed simultaneously. There are standard algorithms for searching. Sequential/linear search algorithms check each element in order until the desired value is found or all elements in the array or Array. List have been checked. Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or Array. List. The binary search algorithm starts at the middle of a sorted Array. List and eliminates half of the Array. List in each iteration until the desired value is found or all elements have been eliminated. 6

Java Quick Reference 13 December 2021 - Accessible methods from the Java library that may be included in the exam Class Constructors and Methods Explanation Array. List Class int size() Returns the number of elements in the list boolean add(E obj) Appends obj to end of list; returns true void add(int index, E obj) Inserts obj at position index (0 <= index <= size), moving elements at position index and higher to the right (adds 1 to their indices) and adds 1 to size E get(int index) E set(int index, E obj) Returns the element at position index in the list Replaces the element at position index with obj; returns the element formerly at position index 7

Java Quick Reference 13 December 2021 - Accessible methods from the Java library that may be included in the exam Class Constructors and Methods Explanation Array. List Class E remove(int index) Removes element from position index, moving elements at position index + 1 and higher to the left (subtracts 1 from their indices) and subtracts 1 from size; returns the element formerly at position index Using Array. Lists 8
![13 December 2021 Can you make arrays larger? String[] list = new String[3]; list[0] 13 December 2021 Can you make arrays larger? String[] list = new String[3]; list[0]](http://slidetodoc.com/presentation_image_h2/080c73f2bac32198f3f88d165858e887/image-9.jpg)
13 December 2021 Can you make arrays larger? String[] list = new String[3]; list[0] = "ant"; list[1] = "bat"; list[2] = "cat"; …. list = new String[5]; • Will the last statement make the array larger? 9
![13 December 2021 Arrays are fixed length list = new String[5]; • Will the 13 December 2021 Arrays are fixed length list = new String[5]; • Will the](http://slidetodoc.com/presentation_image_h2/080c73f2bac32198f3f88d165858e887/image-10.jpg)
13 December 2021 Arrays are fixed length list = new String[5]; • Will the last statement make the array larger? • Answer: • No. • The statement creates a completely new array object (with 5 cells). • The old array object and the information it contains is now garbage unless some other reference variable points to it. • The information in the old array is not transferred to the new array. • To keep the old information, the program must keep a reference to the old array and copy the old information to the new array. This is an issue which can be solved by the use of Array. Lists. null = "no object" 10

Array. List<E> Array. Lists have a default initial capacity of 10 cells (capacity will increase as needed as references are added to the list). 13 December 2021 • Works much like an array with extra methods and features. • Advantages: • The size of an Array. List is not fixed it expands as items are added to it and no information is lost. • Disadvantages: • The elements of an Array. List must be object references, not primitive data like int or double. • How can you use an Array. List to store ints? • You can encapsulate integers in Integer objects to store them in an Array. List. ? • Array. List operations are slightly slower than array operations. • If null is placed in a cell, the cell is regarded as containing data, Array. Lists actually use an ‘unspecified’ means to keep track of empty cells (usually represented in diagrams with an ‘X’). • See Slide 16 for more details of why this is an issue you need to be aware of. • The changing size of Array. Lists causes issues when looping through them – see later 11

Wrapper Classes Primitive type boolean int Corresponding Wrapper class Boolean Integer double float byte long short char Double Float Byte Long Short Character ? Note that primitives consist of lower case letters only, objects start with a capital letter. 13 December 2021 12

13 December 2021 Using Array. Lists • A program must import the java. util package to use Array. List. import java. util. *; /*Note that the * indicates ‘everything’ in the util package, including the scanner. If you need to import more than one thing from a package, it is useful to do this. */ 13

13 December 2021 To create an Array. List: • In one line: • Array. List<Data. Type> Array. List. Name = new Array. List<Data. Type>(); • e. g. //To create an Array. List of String references. Array. List<String> names = new Array. List<String>(); • Array. Lists are generic types which basically means that: The AP CS syllabus always leaves this blank so the Array. List will have a default initial capacity of 10 cells (capacity will increase as needed as references are added to the list). • It only holds objects (as mentioned earlier). • You don’t have to specify the generic type <Type>, since it will default to Object, but it is good practice to specify it to restrict what you allow in your Array. List. The generic type Array. List<Type> is preferred over Array. List because it allows the compiler to find errors that would otherwise be found at run-time. 14

To create an Array. List: 13 December 2021 • In 2 separate lines: • 1. Declare a reference variable for an Array. List. • Array. List<Data. Type> Array. List. Name; • Declares that Array. List. Name is a reference to a future Array. List object. • The future Array. List object will contain an array of references to objects of type E or to a descendant class of E. • 2 - Later on in your code, actually construct an Array. List). • Array. List. Name = new Array. List<Data. Type>(); • e. g. Array. List<Data. Type> names; …. names = new Array. List<Data. Type>(); 15

13 December 2021 Array. List<E> • An Array. List object has a size. • The size is the number of cells that have data in them. • Increases by one each time an element is added. • Cells 0 up through size-1 have data in them. • Data are added in order, before cell N gets data, cells 0, 1, 2, . . . N-1 must hold data. • What do you think this effectively means? What cannot happen? • Meaning that empty cells are not allowed ? between the elements of an Array. List. 16

13 December 2021 Array. List<E> • What is its size? • 3? 17

13 December 2021 Using Array. Lists • To use the methods described earlier: • Array. List. Name. method • e. g. names. add(“Mary”); // Adds the string “Mary” to the Array. List ‘names’. 18

13 December 2021 Array. List<E> • Here is a declaration and construction of a Array. List: • Array. List<String> data = new Array. List<String>(10); • Which of the following statements will work? If not please explain why. • • data. add( "Irene Adler" ); // ? OK data. add( new String("Laura Lyons") ); // ? OK data. add( 221 ); // ? wrong type of argument data. add( new Integer( 221 ) ); ? // wrong type of argument 19

13 December 2021 Autoboxing & Unboxing • Would these statements work in a program? Array. List<Integer> integers = new Array. List<Integer>(); integers. add( 44 ); • You would not expect the 2 nd statement to work, since it seems to be adding primitive data directly into the list of object references. • However, as Javac expects an object reference, when it sees the 2 nd statement it automatically does the equivalent of this: integers. add( new Integer(44) ); // autoboxing • Unboxing works the other direction. int sum = 24 + integers. get(1) ; /* The int inside a wrapper object is automatically extracted if an expression requires an int. So JAVAC automatically extracts the int in cell 1 of data and adds it to the primitive int 24 */ ? Think of wrapping up the data with an object, like wrapping up a gift (& unboxing like unwrapping a gift). 20

Concurrent. Modification. Exception 13 December 2021 /* Precondition: integers is an Array. List and has been populated with at least 3 50’s, 2 of which are consecutive. * / int index = 0; for (Integer integer : integers) { if (integer == 50) integers. remove(index); index += 1; } Output : Concurrent. Modification. Exception ? Caused because a for-each loop relies on the size of the Array being the same during iteration. This would be fine if there was no removal (or add) though. 21

To avoid a Concurrent. Modification. Exception 13 December 2021 /* Precondition: integers is an Array. List and has been populated with at least 3 50’s, 2 of which are consecutive. */ for (int i = 0; i < integers. size(); i++) { if (integers. get(i) == 50) integers. remove(i); } System. out. println(“integers (after removal): ”); for (Integer integer : integers) { System. out. print(integer + “, “); Output: Use a traditional for loop to avoid a Concurrent. Modification. Exception. But do you notice another problem? 22

“Skipping” issue after removal 13 December 2021 /* Precondition: integers is an Array. List and has been populated with at least 3 50’s, 2 of which are consecutive. * / for (int i = 0; i < integers. size(); i++) { if (integers. get(i) == 50) integers. remove(i); } Because removes elements at position index + 1 and higher to the left (subtracts 1 from their indices) and adjusts size, the element after the one just removed, will be ‘ skipped’ (if it is a 50, it will not be removed)! How could we solve this? 23

Solution 1: “Skipping” issue after removal 13 December 2021 /* Precondition: integers is an Array. List and has been populated with at least 3 50’s, 2 of which are consecutive. * / for (int i = 0; i < integers. size(); i++) { if (integers. get(i) == 50){ integers. remove(i); i--; } } // Decrement i if there is an removal. 24

Solution 2: “Skipping” issue after removal 13 December 2021 /* Precondition: integers is an Array. List and has been populated with at least 3 50’s, 2 of which are consecutive. * / for (int i = integers. size() - 1; i >= 0 ; i--) { if (integers. get(i) == 50) integers. remove(i); } // Loop through the Array. List in reverse. 25

Solution 3: “Skipping” issue after removal 13 December 2021 /* Precondition: integers is an Array. List and has been populated with at least 3 50’s, 2 of which are consecutive. * / int i = 0; while (i < integers. size()) { if (integers. get(i) == 50) integers. remove(i); else i++; } // Use a while loop and only increment i if no removal. 26

What is interesting about this line? 13 December 2021 if (integers. get(i) == 50) // integers. get(i) is an object of the Integer wrapper class and we are testing if it is == to 50, which is a primitive int ! ? What must be happening here? ? // 50 is autoboxed to and the equals method used. What should we really write to avoid the need for the answer to the question above? ? if (integers. get(i). equals(new Integer(50)) 27

13 December 2021 A quick note about previous FRQs & printing Array. Lists • Array. Lists implements the List interface. • This is used to be on your syllabus but isn’t any longer. • Therefore, many previous FRQs will mention lists but not to worry as: • List references can also refer to Array. Lists, so just use Array. Lists in FRQs which require Lists and everything should be fine. • The Array. List actually has its own to. String() method so you can actually print an Array. List directly: • e. g. • System. out. println(integers); 28

13 December 2021 Write your own programs: Write your own programs from “scratch”. Of course you should use previous programs for reference, but write your code from “scratch” (do not copy and paste). 29

13 December 2021 Names • Write a program to create two Array. List of names. • Print one Array. List ‘s size before and after populating it with a few names. • Print out the names in the Array. List. • Make sure all methods listed on slides 7 & 8 are used. • When removing names from the list, sometimes add them to the other Array. List. • Create the possibility to remove names that begin with a specified letter. 30

Names 13 December 2021 • Answer these questions : 1. Say that you want a list of int values. But an Array. List can contain only object references. How can you use an Array. List to store your ints ? 2. Examine the following: Array. List<Integer> values = new Array. List<Integer>(); What type of data will values hold? 3. Suppose that the following follows the first three add statements: names. add("Daniel"); a) Where will the reference to "Daniel" be added? Which cell index? b) What is the only restriction when adding items to an Array. List ? 31

Names 13 December 2021 • Answer these questions : 4. What is the size of the Array. List in the picture? 5. Here is a declaration and construction of a Array. List: Array. List<String> data = new Array. List<String>(10); Which of the following statements will work? If not, why not? a) b) c) d) data. add( "Irene Adler" ); data. add( new String("Laura Lyons") ); data. add( 221 ); data. add( new Integer( 221 ) ); 32

Names 13 December 2021 • Answer these questions : 6. What is the index of the first cell of a list? 7. What does null mean in an array? How is this different to what it means in an array? 8. Try to remove a specific name. Write ‘commented out’ code which might produce a ‘Concurrent. Modification. Exception’ and explain. Also write code which will compile and never produce a ‘Concurrent. Modification. Exception’. 33

13 December 2021 Integers • Write a program to create an Array. List of whole numbers. • Populate and print out the numbers in the Array. List. • Use ‘new Integer(1)’, etc… • Can you write ‘Array. List. add(44)’? How come? 34

13 December 2021 Rewrite previous programs • That use Arrays so that they now use Array. Lists. • Make copies, do not delete the previous programs. • To fully use all Array. List method, you must add a ‘delete’ / remove ability to your program. • This is something that is rarely done with arrays as it not easy to code (although it can be done – challenge: How may it be done in an array? ). 35

13 December 2021 Grade yourself • Grade yourself on the vocabulary and learning objectives of the presentation. 36
- Slides: 36