Shared Flashcard Set

Details

SCJP 6 Chapter 7
Flashcards for the Sierra/Bates SCJP 6 exam prep book. Chapter 7 - Generics and Collections
54
Software
Professional
04/11/2011

Additional Software Flashcards

 


 

Cards

Term
What method must be implemented when implementing the Comparator interface?
Definition
int compare(objOne, objTwo);
p. 575
Term
What method must be implemented when implementing the Comparable interface?
Definition
int objOne.compareTo(objTwo)
p. 575
Term
What are the differences with respect to class modification and flexibility when comparing java.lang.Comparable and java.util.Comparator?
Definition
Comparable:
1) must modify the class whose instances you want to sort.
2) only one sort sequence can be created
Comparator:
1) build a class separate from the one that you want to sort
2) many sort sequences can be created
p. 575
Term
With respect to the return values for the compareTo and compare methods (part of the Comparable and Comparator interfaces, respectively), what is the convention for the return values?
Definition
Given:
objOne.compareTo(objTwo) or compare(objOne, objTwo)
Returns:
negative if objOne < objTwo
zero if objOne == objTwo
positive if objOne > objTwo
p. 575
Term
What are two methods provided by java.util.Arrays to sort arrays?
Definition
static void Arrays.sort(arrayToSort)
static void Arrays.sort(arrayToSort, Comparator)
p. 576
Term
For Arrays and Collections, how are searches performed?
Definition
Using the binarySearch() method
p. 576
Term
What is returned as a result of using java.util.Collections or java.util.Arrays to search a collection or array, respectively?
Definition
Successful searches return the int index of the element being searched. Unsuccessful searches return a negative int representing the insertion point. (p. 576)
Term
T/F: A collection/array being searched must be first be sorted.
Definition
T: If you attempt to search a collection/array that has not first been sorted, the results will not be predictable.
(p. 577)
Term
T/F: A collection/array must be searched in the same order in which it was sorted.
Definition
T: A collection/array sorted via natural order (e.g. not sending in a Comparator), must be searched in the same manner. Likewise, a collection/array sorted using a Comparator must be searching using the SAME Comparator.
(p. 577/578)
Term
How do you convert a Collection to an Array?
Definition
Use the toArray() methods of the List and Set classes (p. 579)
Term
What happens when invoking the Arrays.asList() method?
Definition
The array is copied into a list, backed by the specified array. Changes to the returned list "write through" to the array.
(p. 579)
Term
What are the two types of toArray() methods in the List and Set classes?
Definition
One that returns an object array:
Object[] oa = myListOrSet.toArray();
And one that uses the array that you send it as the destination array:
Integer[] ia2 = new Integer[3];
ia2 = myListOrSet.toArray(ia2);
(p. 579)
Term
T/F: The following code correctly demonstrates the use of an iterator:
List d = new ArrayList();
d.add(new Dog("java"));
Iterator i3 = d.getIterator();
while(i3.hasNext()) {
Dog d2 = i3.next();
}
Definition
F
An iterator is obtained by calling .iterator() on a collection:
Iterator i3 = d.iterator();
(p. 580)
Term
What do the hasNext() and next() method of Iterator do?
Definition
hasNext() returns a boolean true if there is at least one more element in the collection being traversed. It does NOT move you to the next element in the collection.
next() returns the next object in the collection AND moves you forward to the element after the eleement just returned.
(p. 580)
Term
T/F: A DuplicateElementException will be thrown if you attempt to add an element to set that already exists in the set.
Definition
F: The duplicate element will not be added to the set, and the add() method will return false.
(p. 581)
Term
Why must one use caution when using TreeSet for your collection?
Definition
TreeSet is a collection whose elements ar sorted, so its elements must be mutually comparable, otherwise a ClassCastException will be thrown (e.g. when trying to add a String to a TreeSet collection whose elements up until that point contained only Integers)
(p. 582/583)
Term
T/F: Overriding the equals() and hashcode() methods is important for classes that are used as map values.
Definition
F: Overriding those methods is important for classes that are used as KEYS in the map, otherwise you may not be able to retrieve your data.
(p. 583)
Term
How are hashCode and equals() used to find data in a map?
Definition
hashCode() is used to find the correct bucket, and equals() is used to find the object in the bucket.
(p. 586)
Term
If you do not override toString() method what will be the output?
Definition
ObjectName@1234
where ObjectName is the class name of the object and 1234 is the hexadecimal representation of the objects hashcode.
Term
What are the limitations if you dont override the equals() method? IE When would it be bad to use a class that does not have an overridden equals method?
Definition
Could not use objects as a key in a hashtable. Would not produce accurate Sets.
p. 545
Term
Which of the following are valid overrides of the equals method?
a.) class Foo { boolean equals(Object o){}}
b.) class Boo {public boolean equals(Boo b){}}
c.) class Goo {protected boolean equals(Object o){}}
d.) class Roo {public boolean equals(Object o){}}
Definition
only d is correct
a - has not access modifier and to override equals you must specify public
b - Argument is not type Object
c - must specify public access modifier not protected
Term
If you override equals() method what should you also override? What contractrual relationship do these two methods have?
Definition
Must also override hashCode()
The contractual relationship is that if two objects are equals then they must also return the same hashcode.
Term
Is it legal to make two objects that arent equal have the same hashcode? What if you make all instances return the same hashcode like public int hashCode() {return 1;}
Definition
Yes, two objects that arent equals() can have the same hashCode(). It just cant be reversed....two objects that are equals() can not have different hashCode().

Also yes, you can (ignorantly) make all instances of an object have the same hashCode().
p553
Term

List alist = new ArrayList();   alist.add(100); //box this

int x = alist.get(0); System.out.println(x);

 

What is the result?

Definition
This code will generate a type mismatch compiler error (Cannot convert from Object to int). One must explicitly cast the result from the list to an (Integer).

pg 609
Term

Which are acceptable ways to call passIt?

 

// Method Signature

public static void passIt(Fruit[] fruits){}

 

satic public void main(String[] args) {

 

  Apple[] apples = {new Apple()};     /

  passIt(apples); //1

  Banana bananas[] = new Bananas[3];

  passIt(bananas);  //2

  Fruit[] fruits = new Fruit{new Fruit()};

  passIt(fruits); //3

}

Definition
all are valid ways to call passIt()
Term

Which of the following compile?

 

1)List<Number> alist= new ArrayList<Integer> ();

2)List<Number> alist= new List<Number>();

3)List<Object> alist= new ArrayList<Object>();

 

 

Definition
Only 3 compiles

pg 610.
Term

Which are acceptable ways to call passIt?

 

// Method Signature

public static void passIt(List<Fruit> fruits){}

 

satic public void main(String[] args) {

  // assume fruit types extend Fruit

  List<Apple> apples = new ArrayList<Apple>();

   passIt(apples);     //1

   passIt(new List <Banana>());  //2

   passIt(new ArrayList<Fruit>()); //3

}

Definition
only line 3 is valid, Generic Types are not polymorphic, but object types are.

pg 611
Term

What is the difference between Collections and Collection?

Definition
Collections is a class, with static utility methods, while Collection is an interface with declarations of the methods.
p559
Term

 

List 4 basic Collections

Definition
List, Sets, Maps and Queues
Term
import java.util.*;
public class LetsNavigate{
public static void main(String[] args) {
  TreeSet<Integer> times = new TreeSet<Integer>();
  for(int i = 1; i <= 10; i++){
    times.add(i);
  }

  System.out.println("lower: " + times.lower(7));
  System.out.println("floor: " + times.floor(6));
  System.out.println("ceiling: " + times.ceiling(5));
  System.out.println("higher: " + times.higher(4));

}

What is the output?
Definition
lower: 6
floor: 6
ceiling: 5
higher: 5
(pg588)
Term

import java.util.*;
public class LetsNavigate{
public static void main(String[] args) {
  TreeMap<String, String> fruitMap = new TreeMap<String, String>();
  fruitMap.put("b", "bananna");
  fruitMap.put("c", "cherimoya");
  fruitMap.put("d", "durian");
 

  SortedMap<String, String> headFruitMap;
  headFruitMap = fruitMap.headMap("c");
 
  headFruitMap.pollFirstEntry()
  fruitMap.put("a", "apple");
  fruitMap.put("e", "eggfruit");

  System.out.println(headFruitMap);
}

Choose all that will be outputted:

 

a)a=apple
b)b=bananna
c)c=cherimoya
d)d=durian
e)e=eggplant

Definition
a (pg590)
Term
import java.util.*;
class PriorityQ {
public static void main(String[] args) {

  int[] intArray = {3,5,2,7};
  PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
  for(int x : intArray) {
    pq.offer(x);
  }
 
  System.out.println(pq.poll());
  System.out.println(pq.peek());
  System.out.println(pq.size());

}

What is the output?
Definition
2
3
3
(pg591)
Term
True/False
For a priority queue with natural ordering:
Spaces sort before characters, and uppercase characters sort before lower case characters.
Definition
True
(p. 595)
Term

What is the result?

  1. Compilation Error 
  2. Exception
  3. Prints "i=42"
public class IDidABadBadThing {
	public static void main(final String... args) {
		final List<Integer> ints = new ArrayList<Integer>();
		insert(ints);
		for (final Object i : ints) {
			System.out.println("i=" + i);
		}
	}

	private static void insert(List ints) {
		ints.add("42");
	}
}

Definition
3. Prints "i=42"
Term
ArrayLists can grow dynamically. (True or False?)
Definition
True.
Term

List myIntegers = new ArrayList();

myIntegers.add(42);

 

Will not compile, primitives must be wrapped prior to adding. True or false?

Definition
False
(p. 607)
Term

To implement the Comparable interface a class must implement a single method.

 

a. compare()

b. compareTo()

c. compareObject()

d. comparable()

Definition
b. compareTo()
Term

When overriding equals() you ____ take an arguement of type Object.

 

a. should never

b. should always

c. should sometimes

Definition
b. should always.
Term

Given the following method signature:

public void addAnimal(List<Animal> animals)

Which of the following may be passed as an argument into the addAnimal method?

a) List<Dog> animals = new ArrayList<Dog>();
b) ArrayList<Dog> animals = new ArrayList<Dog>();
c) List<Animal> animals = new ArrayList<Animal>();
d) ArrayList<Animal> animals = new ArrayList<Animal>();
e) List<Animal> animals = new ArrayList<Dog>();
Definition
c and d.
The only thing that you can pass into the addAnimals method is an argument that extends List and is of generic type Animal (cannot be a subtype of Animal).
a and b fail because of the above.
e will not compile because the generic types on the left and right sides of the equals sign are not the same.
(p. 616, 617)
Term

Given the following method signature:

public void myAnimal(List<? extends Animal> animals)

Answer the following questions:

a) What may be passed as an argument into the myAnimal method? 

b) What limitations, if any, will be enforced within the myAnimal method?

Definition
a) Any argument that is a subtype of List, and is typed for Animal or anything that extends animal
b) Within the addAnimal method, nothing may be added into the collection.
(p. 618)
Term
What is the syntax for using wildcard generic sub-typing with interfaces (e.g. to accept any collection of type Serializable or anything that extends Serializable?)
Definition
The syntax is the same as with classes, and uses the 'extends' keyword, even though that is atypical for interfaces. Thus the following example is legal:
void foo(List list)
(p. 618)
Term

Given the following method signature:

public void myAnimal(List<? super Dog> animals)

Answer the following questions:

a) What may be passed as an argument into the myAnimal method? 

b) What generic specific limitations, if any, will be enforced within the myAnimal method?

Definition
a) Any argument that is a subtype of List, and is typed for Dog or supertypes of Dog
b) The compiler will not enforce any special limitations, and unlike the limitation with 'extends', elements may be added to the animals list.
(p. 619)
Term

What, if anything, is the difference between the following two declarations:

public void foo(List<?> list) //option a
public void foo(List<Object> list) //option b
Definition
With option (a), you can pass in any collection that extends List, with any generic typing (e.g. List, List, etc). However, nothing can be added to that collection within the method. For option (b), you can only pass in a collection that extends List and is of generic type Object (no subtypes of Object allowed, so no List, List, etc). But you can add to the collection within the method. (p. 619, 620)
Term

What, if anything, is the problem with the following code?

import java.util.*;
public class TestWildcards {
  public static void main(String[] args) {
    List<Integer> myList = new ArrayList<Integer>();
    Bar b = new Bar();
    b.doInsert(myList);
  }
}
class Bar {
  void doInsert(List<?> list) {
    list.add(new Dog());
  }
}
Definition
The doInsert method of class Bar is attempting to call .add on the list. This would only be allowed if the parameter to doInsert was declared using the keyword super and an appropriate generic type.
(p. 620)
Term

What, if anything, is the problem with the following code?

import java.util.*;
public class TestWildcards {
  public static void main(String[] args) {
    List<Integer> myList = new ArrayList<Integer>();
    Bar b = new Bar();
    b.doInsert(myList);
  }
}
class Bar {
  void doInsert(List<Object> list) {
    list.add(new Dog());
  }
}
Definition
The TestWildcards class is attempting to pass a list typed as Integer into a method where the parameter is typed as Object.
(p. 621)
Term

T/F: The of the following, if any, are identical:

List<? extends Object> //option a
List<?> //option b
List<Object> //option c
Definition
a and b are identical.
(p. 621)
Term

Which of the following will compile?

  1. List<?> foo = new ArrayList<? extends Animal>();
  2. List<?> list = new ArrayList<Dog>();
  3. List<? extends Dog> list = new ArrayList<Integer>();
  4. List<? extends Animal> aList = new ArrayList<Dog>();
  5. List<? super Animal> list = new ArrayList<Dog>();
  6. List<? super Dog> list = new ArrayList<Animal>();
Definition
2, 4, and 6 will compile
1 will not compile because a wildcard can only be used during reference declaration, not during reference instantiation.
3 will not compile because Integer is not a Dog nor a subtype of Dog.
5 will not compile because Dog is not an Animal or a supertype of Animal.
(p. 623)
Term
When looking at an API, how does one know whether or not a generic (parameterized) type is expected?
Definition
The API will display the parameter placeholder (e.g. public interface List, where is the placeholder for the type you pass in.
(p. 622)
Term

What are the parameterized types defined in the class below, and will it compile?

public class UseTwo<T, X> {
  T one;
  X two;
  UseTwo(T one, X two) {
    this.one = one;
    this.two = two;
  }
  T getT() { return one; }
  X getX() { return two; }
}
Definition
T and X are the parameterized types, and the class will compile. When UseTwo is declared and instantiated (e.g. UserTwo test = new UseTwo()), the types (String, Integer) defined by the programmer will be enforced by the compiler. (p. 625/626)
Term

T/F: The following code, specifying a range (bounds) for the type parameter will compile:

public class AnimalHolder<? extends Animal> { }
Definition

F. At the class level, a type must be used, rather than a wildcard (see example below):

public class AnimalHolder <T extends Animal> { }

(p. 627)

Term
When declaring a generic method in which the type parameter is not defined at the class level, where is the type variable declared?
Definition

Before the return type of the method (see example below):

public <T> void makeArrayList(T t)

(p. 628)

Term
T/F: Bounds may be declared on generic types of methods
Definition

T. The following example is legal:

public <T extends Number> void makeArrayList(T t)

(p. 628)

Term
T/F: Constructors may be declared with generic types not previously declared at the class level.
Definition

T. The following is legal:

public class Radio {
  public <T> Radio (T t) { } //legal constructor
}

(p. 628)

Term

Answer the questions below with respect to wildcards and generics

  1. When can the '?' wildcard syntax be used?
  2. When is something other than the '?' used for wildcard syntax?
  3. In those case(s), what is used in its place?
Definition
  1. When declaring a reference for a variable
  2. When creating generic classes or methods
  3. Any legal Java identifier

(Exam Watch p. 629)

Supporting users have an ad free experience!