CS 165 Exam 2
Can you use the forEach method on any instance of Collection? Where is the forEach method defined?
Yes. It is defined in the Iterable interface which is a super interface for Collection.
Can a collection object be cloned and serialized?
Yes. The concrete classes of Set, List, and Map implements the clone() method in the Cloneable interface.
Are all the methods in the Collections class static?
Yes
Can you use a foreach loop to traverse the elements in any instance of Collection?
Yes.
What is a data structure?
A data structure is a collection of data organized in some fashion.In object-oriented thinking, a data structure is an object that stores other objects, referred to as data or elements. So some people refer a data structure as a container object or a collection object. To define a data structure is essentially to declare a class.
How do you create a list from an array of objects?
A simple way to create a list from an array of objects is to use new ArrayList(Arrays.asList(arrayObject)) or new LinkedList(Arrays.asList(arrayObject)).
Are all the methods in ArrayList also in LinkedList? What methods are in LinkedList but not in ArrayList?
All the methods in ArrayList are also in LinkedList except the trimToSize() method. The methods getFirst, getLast, addFirst, addLast are in LinkedList, but not in ArrayList.
What are the differences between ArrayList and LinkedList? Which list should you use to insert and delete elements at the beginning of a list?
ArrayList and LinkedList can be operated similarly. The critical differences between them are their internal implementation, which impacts the performance. ArrayList is efficient for retrieving elements, and for adding and removing elements from the end of the list. LinkedList is efficient for adding and removing elements anywhere in the list.
Write a statement to find the largest element in an array of comparable objects.
Collections.max(Arrays.asList(arrayObject))
How do you define a class A that implements the Comparable interface? Are two instances of class A comparable? How do you define a class B that implements the Comparator interface and override the compare method to compare two objects of type B1? How do you invoke the sort method to sort a list of objects of the type B1 using a comparator?
How do you define a class A that implements the Comparable interface? public class A implements Comparable<A> { public int compareTo(A o) { return an integer; } } Are two instances of class A comparable? Yes.How do you define a class B that implements the Comparator interface and override the compare method to compare two objects of type B1? public class B implements Comparator<B1> { public int compare(B1 o1, B1 o2) { return an integer; } } How do you invoke the sort method to sort a list of objects of the type B1? list.sort(new B()); To sort an array x of objects of the type B1, use java.util.Arrays.sort(x, new B());
When should a method throw an UnsupportedOperationException?
If a method has no meaning in the subclass, you can implement it in the subclass to throw java.lang.UnsupportedOperationException, a subclass of RuntimeException. This is a good design that you can use in your project. If a method has no meaning in the subclass, you can implement it as follows: public void someMethod() { throw new UnsupportedOperationException ("Method not supported"); }
When using a foreach loop to traverse all elements in a collection, do you need to use the next() or hasNext() methods in an iterator?
No. They are implicitly used in a foreach loop.
What are the differences between the Comparable interface and the Comparator interface? In which package is Comparable, and in which package is Comparator?
The Comparable interface contains the compareTo method and Comparator interface contains the compare method and equals method. Normally, if the objects of a class have natural order (e.g., String, Date), let the class implement the Comparable interface. The Comparator interface is more flexible in the sense that it enables you to define a new class that contains the compare(Object, Object) method to compare two objects of other classes. The Comparable interface is in the java.lang package, and the Comparator interface is in the java.util package. Hide Answer
Describe the Java Collections Framework. List the interfaces, convenience abstract classes, and concrete classes under the Collection interface.
The Java Collections Framework defines the Java API for handling common data structures tasks in Java. It defines classes and interfaces for storing and manipulating data in sets, lists, and maps. A convenience class is an abstract class that partially implements an interface. The Java Collections Framework defines interfaces, convenience abstract classes, and concrete classes.
Which of the following static methods in the Collections class are for lists, and which are for collections? sort, binarySearch, reverse, shuffle, max, min, disjoint, frequency
The methods for lists are: sort, binarySearch, reverse, shuffle, max, min, disjoint, frequency The methods for collections are: max, min, disjoint, frequency *Note that all the methods for collections are also for lists, because lists are collections.
How do you add and remove elements from a list? How do you traverse a list in both directions?
Use the add or remove method to add or remove elements from a list. Use the listIterator() to obtain an iterator. This iterator allows you to traverse the list bi-directional.
import java.util.*; public class Test { public static void main(String[] args) { List<String> list = Arrays.asList("yellow", "red", "green", "blue"); Collections.reverse(list); System.out.println(list); List<String> list1 = Arrays.asList("yellow", "red", "green", "blue"); List<String> list2 = Arrays.asList("white", "black"); Collections.copy(list1, list2); System.out.println(list1); Collection<String> c1 = Arrays.asList("red", "cyan"); Collection<String> c2 = Arrays.asList("red", "blue"); Collection<String> c3 = Arrays.asList("pink", "tan"); System.out.println(Collections.disjoint(c1, c2)); System.out.println(Collections.disjoint(c1, c3)); Collection<String> collection = Arrays.asList("red", "cyan", "red"); System.out.println(Collections.frequency(collection, "red")); } }
(disjoint() returns true if they have NO elements in common, returns false if they have at least one element in common) output: [blue, green, red, yellow] [white, black, green, blue] false true 2
Write a lambda expression to create a comparator that compares two Loan objects by their annualInterestRate. Create a comparator using the Comparator.comparing method to compare Loan objects on annualInterestRate. Create a comparator to compare Loan objects first on annualInterestRate then on loanAmount.
(e1, e2) -> e1.getAnnualInterestRate() < e2.getAnnualInterestRate() ? -1 : e1.getAnnualInterestRate() == e2.getAnnualInterestRate() ? 0 : 1 Comparator.comparing(Loan::getAnnualInterestRate); Comparator.comparing(Loan::getAnnualInterestRate) .thenComparing(Loan:getLoanAmount);
Create a comparator using a lambda expression and using the Comparator.comparing method, respectively, to compare Collection objects on their size.
(e1, e2) -> e1.size() - e2.size() Comparator.comparing(Collection::size)
How do you obtain an iterator from a collection object?
The Collection interface extends the Iterable interface. You can obtain an iterator from a collection using the iterator() method. Hide Answer
Case Study: Bouncing Balls What is the return value from invoking pane.getChildren() for a pane? How do you modify the code in the MutilpleBallApp program to remove the first ball in the list when the button is clicked? How do you modify the code in the MutilpleBallApp program so that each ball will get a random radius between 10 and 20?
The return value is an ObservableList<Node>, which is a subtype of List<Node>. Replace line 75 with the following code: getChildren().remove(getChildren().size() - 1); Change line 133 to radius = Math.random*11 + 10;
What method do you use to obtain an element in the collection from an iterator?
Use the next() method.
Which method can you use to perform binary search for elements in an ArrayList or a LinkedList? Which method can you use to perform binary search for an array of strings?
You can use Collections.binary(list, key) to perform binary search for an ArrayList or a LinkedList and use Arrays.binary(Object[], key) to sort an array of strings.
Which method can you use to sort the elements in an ArrayList or a LinkedList? Which method can you use to sort an array of strings?
You can use Collections.sort(list) to sort an ArrayList or a LinkedList and use Arrays.sort(Object[]) to sort an array of strings. For example, LinkedList<String> list = new LinkedList<>(); list.add("Java"); list.add("Python"); list.add("C++"); java.util.Collections.sort(list); // Sort the list String[] languages = {"Java", "Python", "C++"}; java.util.Arrays.sort(languages); // Sort the array
Suppose each element in list is a StringBuilder, write a statement using a forEach method to change the first character to uppercase for each element in list.
list.forEach(e -> { if (((StringBuilder)e).length() > 0) { char ch = ((StringBuilder)e).charAt(0); if (Character.isLowerCase(ch)) { ((StringBuilder)e).setCharAt(0, Character.toUpperCase(ch)); }; }; });
What method do you use to add all the elements from one collection to another collection?
addAll(Collection c).
Write a statement that sorts an ArrayList of strings named list in increasing order of their last character.
list.sort((e1, e2) -> { if (e1.length() == 0) return -1; else (e2.length() == 0) return 1; else return charAt(e1.size() - 1) - charAt(e2.size() - 1); }
Write a statement that sorts a two-dimensional array of double[][] in increasing order of their second column. For example, if the array is double[][] x = {{3, 1}, {2, -1}, {2, 0}}, the sorted array will be {{2, -1}, {2, 0}, {3, 1}}.
java.util.Arrays.sort(x, (e1, e2) -> (int)(e1[1] - e2[1]));
Write a statement that sorts a two-dimensional array of double[][] in increasing order of their second column as the primary order and the first column as the secondary order. For example, if the array is double[][] x = {{3, 1}, {2, -1}, {2, 0}, {1, -1}}, the sorted array will be {{1, -1}, {2, -1}, {2, 0}, {3, 1}}.
java.util.Arrays.sort(x, (e1, e2) -> { if (e1[1] - e2[1] != 0) return (int)(e1[1] - e2[1]); else return (int)(e1[0] - e2[0]); });
Write a statement that sorts an array named points of Point2D objects on their y values and then on their x values
java.util.sort(points, Comparator.comparing(Point2D::x).thenComparing(Point2D::y));
Suppose that list1 is a list that contains the strings red, yellow, and green, and that list2 is another list that contains the strings red, yellow, and blue. Answer the following questions: a. What are list1 and list2 after executing list1.addAll(list2)? b. What are list1 and list2 after executing list1.add(list2)? c. What are list1 and list2 after executing list1.removeAll(list2)? d. What are list1 and list2 after executing list1.remove(list2)? e. What are list1 and list2 after executing list1.retainAll(list2)? f. What is list1 after executing list1.clear()?
list2 is not changed by all these methods. a. list1 is [red, yellow, green, red, yellow, blue] b. list1 is [red, yellow, green, [red, yellow, blue]] c. list1 is [green] What is list1 and list2 after executing list1.remove(list2); d. list1 is [red, yellow, green] e. list1 is [red, yellow] What is list1 after executing list1.clear(); f. list1 is empty