Programmer II Chapter 3: Generics and Collections Flashcards
What types of method references are there? (4 answers)
- Static methods
- Instance methods on a particular object
- Instance methods on a parameter
- Constructors
What is the result of this code?
15: var heights = new ArrayList < Integer > ();
16: heights.add(null);
17: int h = heights.get(0);
NPE at line 17
What this code prints?
23: List < Integer > numbers = new ArrayList < Integer > ();
24: numbers.add(1);
25: numbers.add(Integer.valueOf(3));
26: numbers.add(Integer.valueOf(5));
27: numbers.remove(1);
28: numbers.remove(Integer.valueOf(5));
29: System.out.println(numbers);
[1]
n lines 24 through 26, we add three Integer objects to numbers. The one on line 24 relies on autoboxing to do so, but it gets added just fine. At this point, numbers contains [1, 3, 5].
Line 27 contains the second trick. The remove() method is overloaded. One signature takes an int as the index of the element to remove. The other takes an Object that should be removed. On line 27, Java sees a matching signature for int, so it doesn’t need to autobox the call to the method. Now numbers contains [1,5]. Line 28 calls the other remove() method, and it removes the matching object, which leaves us with just[1]
Which lines contain compilation errors?
List list = new ArrayList < > ();
Map map = new HashMap < > ();
Map < Long,List < Integer > > mapOfLists = new HashMap < > ();
All lines compile
Which lines compile?
var list = new ArrayList < Integer > (); var list = new ArrayList < > ();
While they both compile, they are not equivalent. The first one creates an ArrayList < Integer > just like the prior set of examples. The second one creates an ArrayList < Object > . Since there is no generic type specified, it cannot be inferred. Java happily assumes you wanted Object in this scenario
What data structures allow null values to be added to them?
The ones that do not involve sorting
Will this code compile?
var byWeight = new Comparator < Duck > () { public int compareTo(Duck d1, Duck d2) { return d1.getWeight()-d2.getWeight(); } };
No
A Comparator must implement a method named compare()
What will this code print?
public static void printList(List < Object > list) {
for (Object x: list)
System.out.println(x);
}
public static void main(String[] args) { List < String > keywords = new ArrayList < > (); keywords.add("java"); printList(keywords); }
printList(keywords); will not compile
List < String > cannot be assigned to List < Object > . We know, it doesn’t sound logical. Java is trying to protect us from ourselves with this one.
Will this compile?
3: List < ? super IOException > exceptions = new ArrayList < Exception > (); 4: exceptions.add(new Exception()); 5: exceptions.add(new IOException()); 6: exceptions.add(new FileNotFoundException());
line 4 will not compile
Line 3 references a List that could be List < IOException > or List < Exception > or List < Object > .
Line 4 does not compile because we could have a List < IOException > and an Exception object wouldn’t fit in there.Line 5 is fine. IOException can be added to any of those types. Line 6 is also fine.
FileNotFoundException can also be added to any of those three types. This is tricky because FileNotFoundException is a subclass of IOException, and the keyword says super. What happens is that Java says, “Well, FileNotFoundException also happens to be an IOException, so everything is fine.”
Given these classes
class A {} class B extends A {} class C extends B {}
Will this compile?
6: List < ? > list1 = new ArrayList < A > ();
7: List < ? extends A > list2 = new ArrayList < A > ();
8: List < ? super A > list3 = new ArrayList < A > ();
9: List < ? extends B > list4 = new ArrayList < A > ();
10: List < ? super B > list5 = new ArrayList < A > ();
11: List < ? > list6 = new ArrayList < ? extends A > ();
Lines 9 and 11 do not compile
Line 6 creates an ArrayList that can hold instances of class A. It is stored in a variable with an unbounded wildcard. Any generic type can be referenced from an unbounded wildcard, making this okay.
Line 7 tries to store a list in a variable declaration with an upper-bounded wildcard. This is okay. You can have ArrayList < A > , ArrayList < B > , or ArrayList < C > stored in that reference. Line 8 is also okay. This time, you have a lower-bounded wildcard. The lowest type you can reference is A. Since that is what you have, it compiles.
Line 9 has an upper-bounded wildcard that allows ArrayList < B > or ArrayList < C > to be referenced. Sinceyou have ArrayList < A > that is trying to be referenced, the code does not compile. Line 10 has a lower-bounded wildcard, which allows a reference to ArrayList < A > , ArrayList < B > , or ArrayList < Object > .
Finally, line 11 allows a reference to any generic type since it is an unbounded wildcard. The problem is that you need to know what that type will be when instantiating the ArrayList. It wouldn’t be useful anyway, because you can’t add any elements to that ArrayList.
Will this compile?
extends T> second(List extends T> list) {
return list.get(0);
}
This will not compile
This method does not compile because the return type isn’t actually a type. You are writing the method. You know what type it is supposed to return. You don’t get to specify this as a wildcard
Given these declarations
class A {} class B extends A {}
Will this method compile?
< B extends A > B third(List < B > list) { return new B(); }
This method does not compile. < B extends A > says that you want to use B as a type parameter just for this method and that it needs to extend the A class. Coincidentally, B is also the name of a class. It isn't a coincidence. It's an evil trick. Within the scope of the method, B can represent class A, or B. Since B no longer refers to the B class in the method, you can't instantiate it.
Will this compile?
< X > void fifth(List < X super B > list) { }
This method does not compile because it tries to mix a method-specific type parameter with a wildcard. A wildcard must have a ? in it.
Suppose that you have a collection of products for sale in a database and you need to display those products. The products are not unique. Which of the following collections classes in the java.util package best suits your needs for this scenario?
A. Arrays B. ArrayList C. HashMap D. HashSet E. LinkedList
B. The answer needs to implement List because the scenario allows duplicates. Since you need a List, you can eliminate options C and D immediately because HashMap is a Map and HashSet is a Set.Option A, Arrays, is trying to distract you. It is a utility class rather than a Collection. An array is not a collection. This leaves you with options B and E. Option B is a better answer than option E because LinkedList is both a List and a Queue, and you just need a regular List.
Suppose that you need to work with a collection of elements that need to be sorted in their natural order, and each element has a unique text id that you want to use to store and retrieve the record.
Which of the following collections classes in the java.util package best suits your needs for this scenario?
A. ArrayList B. HashMap C. HashSet D. TreeMap E. TreeSet F. None of the above
D.
The answer needs to implement Map because you are dealing with key/value pairs per the unique id field. You can eliminate options A, C, and E immediately since they are not a Map. ArrayList is a List. HashSet and TreeSet are Sets. Now it is between HashMap and TreeMap. Since the question talks about ordering, you need the TreeMap. Therefore, the answer is option D.