APCS: Unit 6
True or false? (a) java.util.ArrayList<E> extends java.util.List<E>. (b) An ArrayList<Object> can hold objects of any type. (c) An ArrayList<boolean> holds boolean values.
(a) F (b) T (c) F
True or false? (a) An ArrayList<String> holds references to String objects. (b) An ArrayList<String> can also hold references to Object objects. (c) An ArrayList<Double> can also hold references to Integer objects.
(a) T (b) F (c) F
Suppose nums is an ArrayList<Double>, and nums.size() ≥ 2. Which of the following code segments correctly swap the first and the last elements in nums (True or False) : (a) double temp1 = nums.get(0); double temp2 = nums.get(nums.size() - 1); nums.set(0, temp2); nums.set(nums.size() - 1, temp1); (b) Double temp = nums.remove(nums.size() - 1); nums.add(nums.remove(0)); nums.add(0, temp); (c) int last = nums.size(); Double temp = nums.get(last - 1); nums.remove(last - 1); nums.add(0, temp); temp = nums.get(1); nums.remove(1); nums.add(last, temp);
(a) T (b) T (c) F
Suppose list is an ArrayList<Integer> and n == list.size(). Which of the following calls will throw an IndexOutOfBoundsException? (True or False) (a) list.get(n); (b) list.set(n, 0); (c) list.add(n, 0); (d) list.remove(0);
(a) T (b) T (c) F (d) F
Which of the following ArrayList<E>'s methods returns an object of the type E? (True or False) (a) get (b) set (c) add (d) contains
(a) T (b) T (c) F (d) F
What is an array?
- An array is a block of consecutive memory locations that hold values of the same data type. - Individual locations are called array's elements. - When we say "element" we often mean the value stored in that element. - Rather than treating each element as a separate named variable, the whole array gets one name. - Specific array elements are referred to by using array's name and the element's number, called index or subscript.
Write a for each loop using an array of objects:
- Example of writing our for each loop for the Student array we created earlier. - The variable in the header of the enhanced for loop would be storing the reference to the Student object not a copy of the Student object as in the case of primitive data type. class Student { int marks; } Student[] studentArray = new Student[7]; for ( Student x :studentArray ) { System.out.print(x + ", "); }
Indices (subscripts)
- In Java, an index is written within square brackets following array's name (for example, a[k]). - Indices start from 0; the first element of an array a is referred to as a[0] and the n-th element as a[n-1]. - An index can have any int value from 0 to array's length - 1. - In Java, an array is declared with fixed length that cannot be changed. - Java interpreter checks the values of indices at run time and throws ArrayIndexOutOfBoundsException if an index is negative or if it is greater than the length of the array - 1.
What is a wrapper?
-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: -ArrayList<Double> grades = new ArrayList<Double>(); -grades.add(3.2); -grades.add(2.7); ... -double myGrade = grades.get(0);
What is class composition?
-One of the fundamental activities of any software system design is establishing relationships between classes. -We can use Object composition for code reuse. -Composition is the design technique to implement has-a relationship in classes. -The Car object HAS-A(n) Engine. -The Clock object HAS-A Face. -The Dog object HAS-A Tail. -The Book object HAS-A Title. -The Person object HAS-A Name. -The Car object HAS-A Driver.
ArrayList vs. Array: 1) Construction: 2) Storing a value: 3) Retrieving a value: 4) Doing something to each value that starts with "B": 5) Seeing whether the value "Benson" is found:
1) String[] names = new String[5]; ArrayList<String> list = new ArrayList<String>(); 2) names[0] = "Jessica"; list.add("Jessica"); 3) String s = names[0]; String s = list.get(0); 4) 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")) { ... } } 5) for (int i = 0; i < names.length; i++) { if (names[i].equals("Benson")) { ... } } if (list.contains("Benson")) { ... }
Answer the following questions: 1) By default, what is each number in an array? 2) What is the "slot number" called? 3) What does each slot contain? 4) How are individual elements are accessed in an array? 5) Can array element can be used like any variable? 6) Elements of arrays are numbered starting at what? 7) An index can be any integer ranging from what? 8) An array index must be at least _______ and less than the size of _________. 9) How is an array element identified? 10) What does the declaration create?
1) 0 2) An index 3) An element 4) By an integer index i, using the notation array[i]. 5) Yes (ex: System.out.println(values[4]); ) 6) 0 7) 0 to 9 8) zero / the array 9) By an index 10) Only a reference, initially set to null. An array must be created before it can be used. (Ex of initializing an array: ( arrName = new anyType [length] ) )
Answer the questions regarding an ArrayList: 1) What does it manage? 2) What type do you specify when creating an ArrayList? 3) Can it grow/shrink? 4) What does it do regarding methods? 5) What type of class is it? 6) How are the elements' data type shown?
1) A sequence of objects 2) It must be an object type; it cannot be a primitive type. 3) Yes (You can add items to the list. The default behavior is to add to the end of the list.) 4) Supplies methods for many common tasks, such as inserting and removing elements 5) ArrayList is a generic class: - ArrayList<T> - collects objects of type parameter T: - size method yields number of elements 6) The elements' data type is shown in angle <> brackets and becomes part of the List and ArrayList type. ex: ArrayList<String> words = new ArrayList<String>(); List<Integer> nums = new ArrayList<Integer>(); ArrayList<String> names = new ArrayList<String>(); names.add("Emily"); names.add("Bob"); names.add("Cindy");
Answer the questions regarding array references: 1) What does an array reference do? 2) What does copying the reference do? 3) When you copy an array variable into another, what do both variables refer to? 4) How can you modify the array?
1) An array reference specifies the location of an array 2) Copying the reference yields a second reference to the same array 3) The same array ex: int[] scores = { 10, 9, 7, 4, 5 }; int[] values = scores; // Copying array reference 4) You can modify the array through either of the variables ex: scores[3] = 10; System.out.println(values[3]); // Prints 10
Initialized or not? (Initialization can be postponed until later!!!) 1) String [ ] words; 2) words = new String [ console.readInt() ]; 3) private double[ ] gasPrices; 4) gasPrices = new double[ ] { 3.05, 3.17, 3.59 };
1) No 2) Yes 3) No 4) Yes
Do the following with the array: 1) Print using the value stored: 2) Get array length (not a method!)
1) System.out.println("The value of this data item is" + values[2]); 2) values.length (not a method! Therefore, NO PARENTHESIS FOLLOWING LENGTH!)
Answer the questions regarding for-each loops (enhanced for loop): 1) What are they convenient for? 2) What can use the enhanced for loop for? 3) Can you add/remove elements from a for-each loop? 4) Can you change elements of primitive data types or references to objects within a "for-each" loop?
1) Traversing arrays 2) To visit all elements of an array 3) No 4) No
Answer the questions regarding toString() methods: 1) When is it used? 2) Which class is it defined in, and why is this significant? 3) What does it allow you to do? 4) What is the output, unless overridden? 5) Should all subclasses override this method?
1) When we need a string representation of an object 2) It is a method that is defined in the Object class and thus, every object has one 3) When your class has a toString() method, it allows you do print objects to the console using print() or println() 4) Unless the toString method is overwritten, the output is the class name and the hash code that represents that object in memory. i.e. Person@3e25a5 5) It is recommended. By overriding toString( ) for classes that you create, you allow the resulting strings to be fully integrated into Java's programming environment. For example, they can be used in print( ) and println( ) statements and in concatenation expressions.
Write these ArrayList methods: 1) inserts given value just before the given index, shifting subsequent values to the right 2) removes all elements of the list 3) returns the number of elements in list 4) adds all elements from the given list to this list (at the end of the list, or inserts them at the given index) 5) returns true if given value is found somewhere in this list 6) returns true if this list contains every element from given list 7) returns an object used to examine the contents of the list (seen later) 8) removes any elements not found in given list from this list 9) returns the sub-portion of the list betweenindexes from (inclusive) and to (exclusive) 10) returns the elements in this list as an array
1) add(index, value) 2) clear() 3) size() 4) addAll(list) addAll(index, list) 5) contains(value) 6) containsAll(list) 7) iterator() listIterator() 8) retainAll(list) 9) subList(from, to) 10) toArray()
Do the following: 1) Declare an array variable of type double[]: 2) Initialize the array variable with the array: 3) Specify the initial values when creating an array: 4) Access a value in an array: 5) Create an array of 10 elements through declaration:
1) double[] values; 2) double[] values = new double[10]; 3) double[] moreValues = { 32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65 }; 4) Specify which "slot" you want to use & use the [] operator (ex: values[4] = 35;) 5) double[] values = new double[10];
Do the following regarding ArrayLists: 1) Set an element to a new value: 2) Remove an element at an index: 3) Obtain the value an element at an index: 4) What is one of the most common errors when doing #3?
1) names.set(2, "Carolyn"); 2) names.remove(1); 3) String name = names.get(2); 4) **Bounds error if index is out of range Most common bounds error: int i = names.size(); name = names.get(i); // Error // legal index values are 0 ... i-1
Index values of an array list named sData range from ______ to ________. A) 0, sData.size() - 1 B) 0, sData.size - 1 C) 1, sData.size D) 1, sDate.size()
A
The wrapper class for the primitive type int is ____________________. A) Integer B) intObject C) Int D) There is no wrapper class.
A
Which statement inserts the first element in an array list named players, moving other elements down? A) players.add(0, "John"); B) players.add(1, "John"); C) players.insert(1, "John"); D) players.insert(0, "John");
A
What does a a HAS-A relationship between two classes usually mean?
An instance of one of the classes holds an instance variable of the type of the other variable
How do you construct and add items to an ArrayList?
ArrayList<Type> name = new ArrayList<Type>(); -When constructing an ArrayList, you must specify the type of elements it will contain between < and >. - This is called a type parameter or a generic class. - Allows the same ArrayList class to store lists of different types. ArrayList<String> names = new ArrayList<String>(); names.add("Marty Stepp"); names.add("Stuart Reges");
What is the limitation to arrays?
Arrays have a fixed length
What is auto-boxing?
Automatic conversion between primitive types and the corresponding wrapper classes ex: Double d = 29.95; // auto-boxing; same as // Double d = new Double(29.95); double x = d; // auto-unboxing; same as // double x = d.doubleValue();
Interface Valuable has one method, int getValue(). Consider the following class: public class JewelrySet implements Valuable { private ArrayList<Valuable> items; public int getValue() { int sum = 0; for ( < missing code > ) { sum += item.getValue(); return sum; } } < Constructors and other methods not shown > } Which of the following could replace < missing code >? A. each item in items B. Valuable item : items C. int i = 0; i < items.size(); i++ D. item = items[0]; item != null; item = item.next()
B
What is the output of this program? 1. import java.util.*; 2. class Arraylist { 3. public static void main(String args[]) { 4. ArrayList obj = new ArrayList(); 5. obj.add("A"); 6. obj.add("B"); 7. obj.add("C"); 8. obj.add(1, "D"); 9. System.out.println(obj); 10. } 11. } A) [A, B, C, D] B) [A, D, B, C] C) [A, D, C] D) [A, B, C]
B
The type you specify when creating an ArrayList must be an object type; it cannot be a primitive type. But, we can still use ArrayList with primitive types, how?
By using special classes called wrapper classes in their place. ex: ArrayList<Integer> list = new ArrayList<Integer>();
Rewrite the following loop as a traditional for loop, assuming that ArrayList<String> names has been initialized. for (String s : names) System.out.println(s); A) for (int i = 0; i < names.size() - 1; i++) System.out.println(names.get(i)); B) for (int i = 1; i < names.size() + 1; i++) System.out.println(names.get(i)); C) for (int i = 0; i < names.size(); i++) System.out.println(names.get(i)); D) for (int i = 1; i < names.size(); i++) System.out.println(names.get(i));
C
The wrapper class for the primitive type char is ____________________. A) Char B) There is no wrapper class. C) Character D) charObject
C
What is the output of this program? 1. import java.util.*; 2. class Output { 3. public static void main(String args[]) { 4. ArrayList obj = new ArrayList(); 5. obj.add("A"); 6. obj.add(0, "B"); 7. System.out.println(obj.size()); 8. } 9. } a) 0 b) 1 c) 2 d) Any Garbage Value
C
Which statement accesses the first element of an array list of strings named sData. A) String s = sData(0); B) String s = sData[0]; C) String s = sData.get(0); D) String s = sData.get();
C
What is it called when an object contains the other object, if the contained object cannot exist without the existence of container object?
Composition
To treat primitive type values as objects, you must use ____________________ classes. A) You cannot treat a primitive type value as an object. B) box C) auto D) wrapper
D
If an array is created, what is each of these types automatically set to? Numbers: Boolean: Object References:
Numbers: 0 Boolean: false Object References: null
Write a traditional for loop vs. enhanced for loop (for-each):
Traditional: for (int i = 0; i < values.length; i++) { double element = values[i]; total = total + element; } Using an enhanced for loop: double[] values = . . .; double total = 0; for (double element : values) { total = total + element; }
What does Composition(HAS-A) simply mean?
Use of instance variables that are references to other objects
What happens when there is composition?
With composition, references to the constituent objects become fields of the containing object.
What is the way in which you model objects that contain other objects of a Java program?
With composition, the act of composing a class out of references to other objects.
What is output? ArrayList<Integer> list = new ArrayList<Integer>(); for (int i = 1; i <= 10; i++) { list.add(10 * i); // [10, 20, 30, 40, ..., 100] } for (int i = 0; i < list.size(); i++) { list.remove(i); } System.out.println(list);
[20, 40, 60, 80, 100]
Example of using an index an int variable or any expression that evaluates to an int value:
a [3] a [k] a [k - 2] a [ (int) (6 * Math.random()) ]
Let's pretend for a moment that the ArrayList<Object> class implements the get method in the following manner: public Object get(int i) { < statement > return items[i]; } Which of the following could replace < statement > to make get work as specified in the ArrayList documentation? (True or False) a) Nothing is needed — < statement > can be omitted b) if (i < 0 || i >= items.length) throw new IndexOutOfBoundsException(); c) if (i < 0 || i >= size()) throw new IndexOutOfBoundsException();
a) T b) T c) T
Example of creating an array of objects:
class Student { int marks; } Student[] studentArray = new Student[7]; **The above statement creates an array that can hold references to seven Student objects. The student objects have to be instantiated using the constructor of the Student class.
A prime is an integer that is greater than 1 and has no factors besides 1 and itself. A list of primes can be built gradually. If at some point the list holds the first n primes in ascending order, the next prime is the smallest integer that is greater than the last prime in the list and is not evenly divisible by any of the numbers already in the list. We can start with a list with just one element, 2. Using the above algorithm, write a method that creates and returns an ArrayList<Integer> that holds all the primes below a given number N. Use your method in a program that prints all the primes under 10,000 in ascending order.
import java.util.ArrayList; public class Primes { public static ArrayList <Integer> allPrimes (int n) { ArrayList <Integer> primes = new ArrayList <Integer>(); int p = 2; primes.add(p); while (p < n) { p++; boolean foundDivisor = false; for (int i = 0; i < primes.size() && !foundDivisor; i++) { if (p % primes.get(i) == 0) { foundDivisor = true; } if (!foundDivisor) { primes.add(p); } } return primes; } } public static void main (String[]args) { ArrayList <Integer> primes = allPrimes(10000); for (Integer p : primes) { System.out.println (p + " "); } } }
Write a method public ArrayList<String> concatenate(ArrayList<String> list1, ArrayList<String> list2) that creates and returns a new ArrayList that holds all the elements of list1, in the same order, followed by all the elements of list2, in the same order. Do not use any Java library methods other than List's get and add methods.
public ArrayList <String> concatenate (ArrayList <String> list1, ArrayList <String> list2) { ArrayList <String> result = new ArrayList <String>(); for (String s: list1) { result.add(s); } for (String s: list2) { result.add(s); } return result; }
Write code to show an example of calling the toString method example:
public class Fraction { private int num, denom; ... public String toString () { return num + "/" + denom; } } Fraction f = new Fraction (2, 3); System.out. println (f) ; //f.toString is called automatically Output: 2/3