OCP Flashcards – 3. Generics and Collections

OCP Exam Objective 3 – Generics and Collections

Flashcard OCP.3.Generics.and.Collections.001

How is a generic data type defined?

Click here to view answer
You define a generic class, interface, or method by adding one or more type parameters to it.

 

Flashcard OCP.3.Generics.and.Collections.002

How a client can use a generic class?

Click here to view answer
A client that makes use of a generic class employs parameterized types, replacing the formal parameters with actual parameters.

 

Flashcard OCP.3.Generics.and.Collections.003

What is the convention that covers the use of identifiers for type variables?

Click here to view answer
Java’s naming conventions limit the use of single uppercase letters for type parameters. Though not recommended, using any valid identifier name for type parameters is acceptable.

 

Flashcard OCP.3.Generics.and.Collections.004

How is the matching pair of angle brackets <> called?

Click here to view answer
The diamond operator.

 

Flashcard OCP.3.Generics.and.Collections.005

Is it possible to extend a generic data type?

Click here to view answer
Yes, a generic data type can be extended/implemented by another generic or nongeneric type. In doing so:

  • when a nongeneric class extends a generic class, the derived class doesn’t define any type parameters but passes arguments to all type parameters of its generic base class;
  • when a nongeneric class implements a generic interface, the type parameters follow the interface name;
  • when a generic class implements a generic interface, the type parameters follow both the class and the interface name.

 

Flashcard OCP.3.Generics.and.Collections.006

Can a method be generic?

Click here to view answer
Yes, it can.

 

Flashcard OCP.3.Generics.and.Collections.007

May a generic method be defined in a nongeneric class?

Click here to view answer
Yes, it may.

 

Flashcard OCP.3.Generics.and.Collections.008

Where must a generic method define its type parameters, and why?

Click here to view answer
A method’s type parameter list is placed just after its access and nonaccess modifiers and before its return type. The reason: since a type parameter could be used to define the return type, it must be known before the return type is used.

 

Flashcard OCP.3.Generics.and.Collections.009

What are the restrictions that apply to bounded type parameters?

Click here to view answer
For a bounded type parameter, the bound can be a class, an interface, or an enum, but not an array. All cases use the keyword extends to specify the bound. If the bound is an interface, the implements keyword is NOT used.

 

Flashcard OCP.3.Generics.and.Collections.010

What does the wildcard ? represent in generic types?

Click here to view answer
The wildcard ? represents an unknown type. Can be used to declare the type of:

  • a parameter;
  • a local, instance, or static variable;
  • a return value.

Cannot be used as a type argument:

  • to invoke a generic method
  • to create a generic class instance
  • for a supertype.

 

Flashcard OCP.3.Generics.and.Collections.011

Is the following assignment valid, and why it is so?

List<Object> list = new ArrayList<String>();

Click here to view answer
No, it is not valid. Inheritance and polymorphism in particular do not apply to type parameters.

 

Flashcard OCP.3.Generics.and.Collections.012

What is the drawback of using the wildcard ? in declaring variables or method parameters?

Click here to view answer
We lose the functionality of adding and retrieving objects to / from a collection.

 

Flashcard OCP.3.Generics.and.Collections.013

How can we restrict types that are to be used as arguments in a parameterized type?

Click here to view answer
By applying bounds such as extends and super.

 

Flashcard OCP.3.Generics.and.Collections.014

When can the keyword extends be used in wildcards? Select one:

  • only for classes;
  • only for interfaces;
  • both are possible.
Click here to view answer
In upper-bounded wildcards, the keyword extends is used for both a class and an interface.

 

Flashcard OCP.3.Generics.and.Collections.015

What does the use of the extends and super wildcards restrict?

Click here to view answer
For collections defined using upper-bounded wildcards, it becomes impossible to add any objects. On the other hand, we can iterate and read values from such collections.

The use of super makes it virtually impossible to work with collection’s elements, although we can still add more of them to the data structure.

 

Flashcard OCP.3.Generics.and.Collections.016

Is it permitted to write something like <? extends some_final_class>?

Click here to view answer
Yes, it is indeed possible to use final classes in upper-bounded wildcards. Although class X extends String{} is invalid, <? extends String> will compile successfully.

 

Flashcard OCP.3.Generics.and.Collections.017

How can we ensure that type arguments follow a specific IS-A relationship?

Click here to view answer
It is possible to restrict the use of type arguments to a type and its supertypes or base types by using <? super Type>, where Type refers to a class, interface, or enum.

 

Flashcard OCP.3.Generics.and.Collections.018

What is a type erasure?

Click here to view answer
Type information is deleted during the compilation process; this is called type erasure.

 

Flashcard OCP.3.Generics.and.Collections.019

How many versions of the bytecode the Java compiler produces for a generic class?

Click here to view answer
When a generic class is compiled, the compiler does not generate multiple versions of the .class files.

 

Flashcard OCP.3.Generics.and.Collections.020

How is type erasure performed in practice?

Click here to view answer
The compiler erases the type information by replacing all type parameters in generic types with Object (for unbounded parameter types) or their bounds (for bounded parameter types).

 

Flashcard OCP.3.Generics.and.Collections.021

What are bridge methods?

Click here to view answer
The Java compiler might need to create additional methods, referred to as bridge methods, as part of the type erasure process. Typically it happens when overriding method’s signature stop matching after type erasure. For more details ref.to https://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html.

 

Flashcard OCP.3.Generics.and.Collections.022

What is the base type for List<String>?

Click here to view answer
It’s Iterable<?> because List<E> extends Collection<E>, which in its own turn extends Iterable<E>.

Java Collections Framework Cheat Sheet (editable true PDF: Collections_Chart_Colored.pdf; same but black&white: Collections_Chart_BW.pdf):

 

 

Flashcard OCP.3.Generics.and.Collections.023

What is an unchecked warning?

Click here to view answer
An unchecked warning gets thrown if the compiler can’t ensure type safety. This happens when the compiler doesn’t have enough type information to perform all type checks:

List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<>();         // allowed since 1.7
List<String> list3 = new ArrayList();           // throws unchecked warning

 

Flashcard OCP.3.Generics.and.Collections.024

How does the compiler infer the type parameters in a generic method invocation?

Click here to view answer
The Java compiler cannot infer the type parameters by using the diamond in the case of generic methods. Instead, it uses the type of the actual arguments passed to the method:

class Test{
    <T> void run(T obj){ System.out.println(obj);  }
    public static void main(String[] args) {
        new Test().run("Hello!");
        new Test().<String>run("Hello again!");
//        new Test().<>run("Hello");               // INVALID
    }
}

 

Flashcard OCP.3.Generics.and.Collections.025

What is a raw type?

Click here to view answer
A raw type is the name of a generic class or interface without any type arguments (cf.Flashcard OCP.3.Generics.and.Collections.022 a few lines above).

 

Flashcard OCP.3.Generics.and.Collections.026

Is it possible to assign a parameterized type to its raw type?

Click here to view answer
Yes, it is; however, the reverse throws a compiler warning.

 

Flashcard OCP.3.Generics.and.Collections.027

What happens when a parameterized type gets assigned to a raw type?

Click here to view answer
When we assign a parameterized type to its raw type, we lose the type information.

 

Flashcard OCP.3.Generics.and.Collections.028

What is the Collection<E> datatype?

Click here to view answer
This is the root interface in the collection hierarchy that represents a group of objects, known as its elements.

 

Flashcard OCP.3.Generics.and.Collections.029

What are the concrete classes that directly implement Collection<E>?

Click here to view answer
Trick question! There are no direct concrete implementation of Collection<E>; it’s extended by more specific interfaces such as Set<E>, List<E>, and Queue<E>, and abstractly implemented by the AbstractCollection<E> class.

 

Flashcard OCP.3.Generics.and.Collections.030

Briefly describe the Set, List, Queue and Map interfaces.

Click here to view answer
A Set is a collection that contains no duplicate elements, a List is an ordered collection that allows to store duplicates, Queues hold elements prior to processing (usually in the FIFO fashion), and Maps are objects hat map keys to values and, as such, cannot contain duplicate keys.

 

Flashcard OCP.3.Generics.and.Collections.030

Pair the element(), peek(), remove(), poll(), push(), pop(), add() and offer() methods of the Deque interface and briefly describe their differences.

Click here to view answer
            Throws exception      Returns special value
Insert           add(e)                 offer(e)
Remove           remove()               poll()
Examine          element()              peek()

As for push() and pop(), they affect the head of the queue by inserting and removing an element, respectively.

 

Flashcard OCP.3.Generics.and.Collections.032

Why should classes redefine their hashCode() method?

Click here to view answer
Classes should override their hashCode() method to enable collections such as HashSet, etc. to store their elements efficiently.

 

Flashcard OCP.3.Generics.and.Collections.032

Briefly describe a TreeSet and its requirements.

Click here to view answer
A TreeSet stores all its unique elements in a sorted order, which is defined by their natural order (achieved by implementing the Comparable interface) or by passing a Comparator while instantiating a TreeSet.

In the absense of either a Comparable implementation or Comparator, an attempt to add an element to a TreeSet will throw a runtime exception.

 

Flashcard OCP.3.Generics.and.Collections.034

What is the java.lang.Comparable interface used for? Provide a brief description.

Click here to view answer
The Comparable interface is used to define the natural order of the objects of the class that implements it. Comparable is a generic interface (using T as type parameter) that defines only one method, compareTo(T obj), which compares this object to obj passed to it as its argument.

 

Flashcard OCP.3.Generics.and.Collections.035

What does compareTo() return?

Click here to view answer
Method compareTo() returns a negative integer, zero, or a positive integer if this object is less than, equal to, or greater than the passed-in object.

 

Flashcard OCP.3.Generics.and.Collections.036

What is the java.util.Comparator interface?

Click here to view answer
The Comparator interface is used to define the sort order of a collection of objects, without requiring them to implement this interface.

 

Flashcard OCP.3.Generics.and.Collections.037

What is the signature of the comparison method defined by Comparator?

Click here to view answer
It’s

int compare(T obj1, T obj2)

 

Flashcard OCP.3.Generics.and.Collections.038

Offer some examples where a Comparator is typically used.

Click here to view answer
A Comparator is commonly used in sort methods such as Arrays.sort() and Collections.sort() in order to sort a collection. Also, a Comparator object may be passed to collection classes like TreeSet and TreeMap that require custom-ordered elements.

 

Flashcard OCP.3.Generics.and.Collections.039

What are telltale signs that a custom class should rely on a Comparator rather than Comparable?

Click here to view answer
The Comparator interface is used to specify the sort order for classes that

  • don’t define a natural sort order;
  • may need to work with an alternative sort order;
  • don’t allow modification to their source code so that natural ordering can be added to them.

 

Flashcard OCP.3.Generics.and.Collections.040

What are common, collection-wise features of the primitive Wrapper classes?

Click here to view answer
The primitive Wrapper classes defined in java.lang:

  • are immutable,
  • implement Comparable,
  • and therefore define their natural order.

 

Flashcard OCP.3.Generics.and.Collections.041

What are implicit conversions for integer and decimal literals when assigning to Wrapper variables?

Click here to view answer
Integer literal values are implicitly converted to Integer objects and decimal literals to Double objects.

 

Flashcard OCP.3.Generics.and.Collections.042

How many conversion steps can the compiler perform implicitly?

Click here to view answer
Only one.

 

Flashcard OCP.3.Generics.and.Collections.043

Why does the following LOC fail compilation?

Double d = 10;

Click here to view answer
Because the integer literal 10 gets converted to Integer, which is not assignment-compatible with Double.

 

Flashcard OCP.3.Generics.and.Collections.044

Are the objects of different wrapper classes with the same values equal?

Click here to view answer
No, they aren’t.

 

Flashcard OCP.3.Generics.and.Collections.045

What is the natural ordering of String objects?

Click here to view answer
String objects are sorted according to the so-called lexicographical order, which implies that capital letters precede the lower-case ones.

 

Flashcard OCP.3.Generics.and.Collections.046

What are autoboxing and unboxing?

Click here to view answer
Autoboxing is the automatic conversion of a primitive data type to an object of the corresponding wrapper class, while unboxing is the reverse process.

 

Flashcard OCP.3.Generics.and.Collections.047

True or false: “The keyword extends applies to either an interface or a subclass to indicate that generic parameters are bounded”?

Click here to view answer
False: “sublcass” should be replaced with “superclass”.

 

Flashcard OCP.3.Generics.and.Collections.048

Which interface should be implemented to sort a collection’s elements in an order other than the default one?

Click here to view answer
Comparator

 

Flashcard OCP.3.Generics.and.Collections.049

Which operator instructs the compiler to use type inference on an empty set of type parameters?

Click here to view answer
The diamond operator, <>

 

Flashcard OCP.3.Generics.and.Collections.050

How would you create a list of OCP exam takers whose score is above 90?

Click here to view answer
For example:

examTakersList.stream().filter(x -> x.getScore() > 90).collect(Collectors.toList());

 

Flashcard OCP.3.Generics.and.Collections.051

If objectA.compareTo(objectB) returns a negative integer, which object is greater?

Click here to view answer
objectB

 

Flashcard OCP.3.Generics.and.Collections.052

Which Collection type doesn’t allow duplicate elements?

Click here to view answer
Set

 

Flashcard OCP.3.Generics.and.Collections.053

How would do you sort elements in a Collection?

Click here to view answer
For example, by using the Collections.sort() method or by calling .stream().sorted() on the collection.

 

Flashcard OCP.3.Generics.and.Collections.054

When is the diamond operator can be used with a constructor to infer a generic parameter type?

Click here to view answer
When the type is explicitly specified in the variable declaration part.

 

Flashcard OCP.3.Generics.and.Collections.055

Which Stream methods can be used to limit the number of elements taken from a collection?

Click here to view answer
filter(), distinct(), skip() and limit()

 

Flashcard OCP.3.Generics.and.Collections.056

Can generic parameter types be directly instantiated?

Click here to view answer
No, it is not possible due to type erasure: during compilation, T is replaced with Object, but T is supposed to be anything that extends Object, so the assignment won’t work:

class Test<T>{
    void run(){
        T objT1 = new T();            // INVALID
        T objT2 = (T) new Object();
    }
}

 

Flashcard OCP.3.Generics.and.Collections.057

Which method must a class implement in order to use the Comparable interface: compare() or compareTo()?

Click here to view answer
compareTo()

 

Flashcard OCP.3.Generics.and.Collections.058

Which interface do the java.util.Collections.sort() and java.util.Arrays.sort() method rely upon to sort a collection in its natural order?

Click here to view answer
Comparable

 

Flashcard OCP.3.Generics.and.Collections.059

Suppose, Dog is a subclass of Animal. Can ArrayList<Animal> accept a reference variable of the Dog type?

Click here to view answer
Yes, it can.

 

Flashcard OCP.3.Generics.and.Collections.060

Which interface ensures that elements are placed into a Map according to their natural order?

Click here to view answer
SortedMap

 

Flashcard OCP.3.Generics.and.Collections.061

By looking at the following LOC, can you tell which type the myBook collection is of?

myBooks.forEach(book -> System.out.println(book));

Click here to view answer
Well, not really; one thing is clear, though: it isn’t a Map because Map#forEach() accepts a BiConsumer.

 

Flashcard OCP.3.Generics.and.Collections.062

What is the primary storage and retrieval mechanism for a Map?

Click here to view answer
The one that makes use of name/value pairs.

 

Flashcard OCP.3.Generics.and.Collections.063

What is the difference between the types Collections and Collection?

Click here to view answer
Collection is an interface, Collections is a utility class.

 

Flashcard OCP.3.Generics.and.Collections.064

Which interface and method would allow you to visit all elements in a Collection without using Java 8 streams?

Click here to view answer
The forEach() method defined in the Iterable interface.

 

Flashcard OCP.3.Generics.and.Collections.065

Why does the following class fail compilation?

class Test<T>{
    static void doStuff(){
        List<T> list = new ArrayList<>();
    }
}
Click here to view answer
It’s because class-level type parameters are only in scope for instance methods and fields, so they cannot be used in a static context.

Illustration of how class-level and method-level type variables differ from each other:

class Test<T>{
    T name;
    Test(T name)    {  this.name = name;   }
    void run(T arg) {  System.out.println( arg.getClass().getSimpleName() );   }

    static <T> List<T> doStuff(T elem){        // this T is completely different
        List<T> list = new ArrayList<>();      // from the previous one
        list.add(elem);
        return list;
    }

    public static void main(String[] args) {

        new Test<>("Name").run("Age");                                              // String
        System.out.println(   doStuff(1).get(0).getClass().getSimpleName()     );   // Integer

    }
}

 

Flashcard OCP.3.Generics.and.Collections.066

The String class implements Comparable but StringBuilder does not. Why is that?

Click here to view answer
What’s more, StringBuilder overrides neither hashCode() nor equals(). It’s because StringBuilder‘s purpose in life is to make Strings, which we then work with by comparing or storing them in collections, etc.

 

Flashcard OCP.3.Generics.and.Collections.067

Why the Collections.sort() method is overloaded for List and List, Comparator only? What about Set and Queue?

Click here to view answer
Sets and Queues can be sorted automatically at the moment of instantiation by specifying SortedSet and PriorityQueue, respectively; alternatively,  we can call the ArrayList(Collection) ctor to pass this newly created ArrayList object to Collections(List).

 

Flashcard OCP.3.Generics.and.Collections.068

Which methods will return the first element in a Deque?

Click here to view answer
There are 5 of them:

element()            // retrieves w/o removing; throws NSEE on empty Deque
peek()               // retrieves w/o removing; returns null when Deque is empty
remove(zero arg)     // retrieves and removes; throws NSEE on empty Deque
poll()               // retrieves and removes; returns null when Deque is empty
pop()                // throws NSEE on empty stack

Queue‘s remove() as well as stack-based pop() are equivalent to Deque‘s removeFirst(). Although pop() seems redundant, it exists because Deque replaced the legacy Stack class, which defined the push/pop combo.

Leave Comment

Your email address will not be published.