Study your flashcards anywhere!

Download the official Cram app for free >

  • Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off

How to study your flashcards.

Right/Left arrow keys: Navigate between flashcards.right arrow keyleft arrow key

Up/Down arrow keys: Flip the card between the front and back.down keyup key

H key: Show hint (3rd side).h key

A key: Read text to speech.a key


Play button


Play button




Click to flip

67 Cards in this Set

  • Front
  • Back
If you print an object that hasn't overridden toString(), what will you get?
Class name + @ + unsigned hexadecimal hash code
What's a cute nickname for toString()?
"spill your guts" method
If you fail to override equals(), what is it's default behavior.
Failure to override equals means default reliance on == will occur. This means objects are only equal when they are the same object (both refs point to same object). It ignores any conceptual equality - meaning if 2 different objects have insides that should be considered equal -- using == will not be able to see this equality.
When overridding equals, what are the steps to complete?
1. Make sure the Object sent in is of the correct type
(obj instanceof MyClass)

NOTE: Generally don't want to cast right away because you might get a ClassCastException. instanceof operator allows graceful failure.

2. Cast the object

3. Compare the attributes we care about (ideally as few as possible)
class Foo {
boolean equals(Object o){}

It fails to compile for TWO reasons.

1) Method fails to return a boolean.

2) This overridden method is weaker than original because equals() (and hashCode() and toString() are PUBLIC!)
class Foo {
public float hashcode(){
return 1.1;

No. But not for the reason you might think.

1.1 is a double and compiler complains that it'll loose precision when converted to a float.

This is not an override! It's an overload because the method name wasn't camel cased!

To override you need to spell it this way:
hashCode() <-- Capital C!
What is the equals() contract?
reflexive - x.equals(x) is true

symmetric - x.equals(y) true if and only if y.equals(x) is true


consistent - multiple calls return same results

for non-null x, x.equals(null) should return null
What is the join contract between equals() and hashCode()?
If 2 objects are equal, they should have the same hashcode.

If 2 objects output different hashCode() outputs, then equals() should output false.

NOTE: If 2 objects are NOT equal they certainly can have the same hash value and if they produced the same hashCode() output it doesn't guarantee that the objects are equal().
Summarize what a hashCode() helps you find.
A hashCode() helps you find the right bucket of stuff, then you need to use equals() to find the right thing inside that bucket.

There certainly are instances where all buckets have items and also the situation where all items are placed in 1 bucket (which defeats the whole point of hashing. i.e. hashCode(){return 1;}
What is the rule of thumb when overriding equals() in regards to hashcodes?
RULE OF THUMB: if you override equals(), override hashCode() too.
How do transient variables affect equals() and hashCode()?
Simply, they screw with them. If an object with transient vars is serialized and restored, the state of object has changed. If equals() and hashCode() use such transient variables, the same object outputs different results.

This breaks the consistency part of our contract. Will it compile & run? Yes. But that doesn't mean it's correct.
Name 7 interfaces used in the collections framework.

Name 13 concrete classes used in the collections framework.



<<List>> & <<Queue>>




Also, utility classes that descend from Object and found in java.util:
(notice that both of these end with an "s")
When would you use ArrayList over LinkedList
When you want fast access and aren't doing lots of insertion & deletion
What concrete classes of the collections framework also implement the RandomAccess interface?

NOTE: RandomAccess is a "marker" interface
How has LinkedList changed as of Java 5?
It now implements the Queue interface.
Sets, conceptually, simply imply that the items in it are unique, but not ordered. Does a LinkedHashSet guarantee order?
Sorted is ordering based on the value of the objects being considered. What are the 3 INHERENTLY SORTED concrete classes in the collections framework?
What's notable about the HashTable class?
That if it exists, it's not part of java 5 core classes.

Hashtable, though, is part of Java 5 coure. (difference? the core class is NOT camel cased)
In a TreeMap what is sorted, the elements or the keys?
The keys.
What's the BIG idea behind Generics?
To be able to created collections that we know not only hold things of type Object, but of more specific types. While generics can be added to any class, they main intention was to enhance the collections framework
Do you ever create an instance of List?
No. List is an interface. You create a concrete collection that implements List.

List<String> lis = new ArrayList<String>();
How do you sort a List? Note that Lists aren't inherently sorted but they do have an order?
You can use this static method from the Collections class:

Collections.sort(List l);

ALL items of list must implement an interface called Comparable OR you must use an overloaded method:

Collections.sort(List l, Comparator c);
ArrayList al = new ArrayList();

What prints?
[c, b, a]
[a, b, c]
What part of the collections framework allows you to sort arrays?
java.util.Arrays.sort(array of primitives or objects)

Note that ArrayList would NOT be sorted with this class because it's first a collection and only internally functions as an array. Use java.util.Collections.sort() to sort an ArrayList
Arrays.sort() and Collection.sort(), when not passed a Comparator, need Comparable objects to do their sorting. How does an object become Comparable?
Comparable objects must implement the Comparable interface

Thus, they must implement this method:
int compareTo(Object obj)

Required return values:
negative - less than obj
zero - equal to obj
postivie - greater than obj

Notice that these objects then need equals() overriden to give the correct conceptual results of equality

NOTE: W/ generics, if the implementation includes a generic type, then the implementation of the argument in the compareTo method goest from (Object obj) to the type declared by the generic.
What's the difference between Comparable and Comparator?
Comparable is implemented by an object so that object can say, "I have the power to compare myself to something." Notice that the object itself owns the comparing power.

Comparator is a shift of that comparing power to a third party. It stands outside the 2 things being compared, considers them, and returns a comparison result.

SO... if you pass a sort a Comparator then the group will be compared by that 3rd party, otherwise each object but own comparing power themselves by being Comparable.
class C extends Comparator<String> {
int compare(String s1, String s2) {
return s1.compareTo(s2);

What's wrong with this code?
1) Comparator is an interface not a class. It should be implemented rather than extended.

2) All interface methods are inherently public. When you implement an interface method you must put the public modifier on or the compiler complains your attempt to implment a weaker form of the method.
When using the java.util.Arrays.sort() method to sort an array of primitives, can you use a Comparator?
No. An overloaded version of the sort() method includes an option for a Compartor only when the array is an Object[] array.

Arrays of primitives are ALWAYS sorted by their natural order.
What are the qualities of searching as implmented in Collections and Arrays?
performed using binarySearch() method

found item returns int index

unfound item returns int index of where item would be inserted. This index will be increased by 1 and negated to indicate that it did not find the element.
(i.e. if item would be inserted at index=0, return would be -1)

collection/array must be sorted before being searched(the results will be unpredictable otherwise)

if sorted in natural order must be searched in natural order (must not send Compator obj that sorts in other way)

if sorted using a Comparator, must be searched using the same Comparator.
How do you convert Lists to arrays and arrays to lists?
List has a toArray() method (as does Set).
NOTE: toArray has 2 flavors. Either return an array or populate an array you send as an argument.

NOTE: after call to asLlist(), changes to either the array or the new List will cause change in the other... they are now joined at the hip. We say that the List is "backed" by the original array
Though iterators still exist, what has taken its place in most iteration jobs?
The new, Java 5 for loop (Type obj : group to iterate through)
Name 2 important methods of an Iterator?
What is an iterator and how might you get one associated with a List you want to walk through?
An iterator is a walkthrough object associated witha specific collection. To get one out of a list:

Iterator it = listObject.iterator();

NOTE: As with most collections it works with Objects unless declared differently with generics

Iterator<Dog> it = listOfDogs.iterator();
(assumes listOfDogs is a List<Dog> )
If you're making a TreeSet what has got to be true of it's elements.
Where there is a sort going on, the items better be Comparable or a Comparator better be sent to the sort.
If you're using Maps, what should be true of its keys?
They should have overridden equals() and hashCode().

The hashCode() will find the right bucket and equals() will find the right item in that bucket.
If you use some Object as a key to add an element into a hash, and you then change the state of the Object what happens?
If the hashcode() is affected by the state change, then the key might now not map to the right bucket.

If the equals() method is affected by the state change, then once in the right buckect, you might not be able to find the right item in that bucket.
Name 3 important methods in a PriorityQueue.
E peek() - return (but don't remove) item off front of queue

E poll() - remove and return item off front of queue

boolean offer() - add to the queue
How are PriorityQueues ordered?
User define order. That order could be anything, from natural ordering to use of a Comparator.
What should be true of a PriorityQueue's elements?
If the PriorityQueue is not using a Comparator, the elements need to be Comparable (because items are sorted by the nature of the structure. If your sorting you need to have a Comparator or be Comparable).
pg. 568 and 569 for answers!
How do spaces, upper case, and lower case "naturally" order?
Spaces first.
Upper case second.
Lower case last.
What are the major methods of the Arrays utility class?
static List asList(Object[] a)
*binds new List to array

static int binarySearch(Object[], key[, Comparator])
static int binarySearch(primitve[],key)
static int binarySearch(T[], key)
* T[] means sorted array where T represents a generic type

static boolean equals(Object[], Object[])
static boolean equals(primitive[], primitive[])
* equal if same number of elements and every corresponding pair of elements is equal

public static void sort(Object[][, Comparator]))
public static void sort(primitive[])
public static void sort(T[], Comparator)

public static String toString(Object[])
public static String toString(primitive[])
*A pretty cool way to pretty-print arrays of primitives and Objects
What are the major methods of the Collections utility class?
public static int binarySearch(List, key)
public static int binarySearch(List, key, Comparator)

public static void reverse(List)

public static Comparator reverseOrder()
* Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

public static void sort(List)
public static void sort(List, Comparator)
Methods available to a List interface?
boolean add(element)
boolean add(index,element)

object remove(index)
boolean remove(object)
* object removal only removes first instance

boolean contains(object)

int indexOf(object)

object get(index)

Iterator iterator()
int size()

Object[] toArray()
Methods available to a Set interface?
boolean add(element)
boolean remove(object)

boolean contains(object)

Object[] toArray()

Iterator iterator()
int size()
Methods available to a Map interface?
key = some object
value = some object

Object put(key, value)
* Returns null or previous value associated with key if it existed. Old is replaced with new in that case.

value remove(key)

boolean containsKey(key)
boolean containsValue(value)

value get(key)

Set keySet()

int size()
What is generics?
Generics is a way to have the compiler add type checking to collections of types other than type Object. Generics can be used for things besides Collections but this is the main thrust of generics.
Where can you add Generics?
Anywhere you declare or instantiate a collection

1) collection declaration
2) collection instantiation
3) methods parameters
4) method return types
Will legacy collections code where casting was done on item retrieval break when reading from a Collection that's been made type specific with generics?
No. It should work fine.
Will legacy collections code where items were added to a collection break when adding to a collection made type specific with generics?
A problem might occur.

When a generic typed list is sent to a legacy piece of code that doesn't use generics, the collection functions like the old type of collections. Adds at that point simply need to be of type Object. There is the possibility that the real type of such and added Object might not be compatible with the generic-type set on the collection in the newer part of the code. It will compile AND it will run!

Only when you then go to use that problematic Object in the manner of the type of the other objects, might a problem occur.

i.e. Consider a List<Integer>. A legacy piece of code will see only a List and add an object that could be a String. You now have a collection your newer code expects to be all Intgers with a String in it! Because generics are erased before runtime, the system runs this w/out problem as it sees collections, at runtime, only as groups of objects.

It's when you try to treat the String object like an Integer that probs will occur.

NOTE: Generics are basically a convenience and a safety-net of typing. This safety net goes away when you let legacy code add to your collection
In regards to generics, when does the Java 5 compiler WARN you about unchecked or unsafe operations?
Whenever you add to a collection and that collection is not marked by generics, you'll get the warning. If you simply choose not to use to generics, then any add will cause this warning.
class Parent{}
clase Child extends Parent{}
List<Parent> l = new ArrayList<Child>();

What happens?
Compiler error. Generic types are NOT polymorphic like classes. They must match exactly. No sub or supertype substitutions are allowed.
Foo f = new Foo();
List<Object> l = new ArrayList<Object>();
Collections.binarySearch(l, f);

What happens?
Compiler error. Because there is a generics-typed list being used in binarySearch, it's generic type must match EXACTLY the type of the object being searched for (f).

In this case we have List of <Object> and a search object of <Foo>. The both need to be Object or Foo for this search to work.
public ff() {
Cat[] cats = {new Cat()};
public void addAnimal(Animal[] animals) {
animals[0] = new Dog[];

What happens? If these were generic collections and not arrays what would happen differently?
This example compiles but a runtime error occurs (because the complier doesn't know in addAnimal that it's animals array is really a cat[] that can't hold dogs. All the compiler rules are satisfied, but the runtime will catch.

The difference with generics is that the programmer would essentially shift this runtime error into a compile time error, which are much easier to fix.
void changeAnimals(List<? extends Animal> animals) {
animals.add(new Dog());

What happens?
Compile error. If you used a wild card with "extends" you're saying the generic type of this list might be some subtype of Animal, but you promise that you will not add to the collection. Compiler sees the add and throws an error.

Why can't you add? Imagine you send in a List of generic subtype Cat. You shouldn't be able to add a Dog. And since generic errors like this can't be caught at runtime, have to catch them here.
void changeAnimals(List<? super Dog> animals) {
animals.add(new Animal());

Why does the compiler complain?
It doesn't.
What different things do generic-type and base type refer to?
Think of base type as the type of the collection and the generic type as the type of elements inside the collection.
void changeAnimals(List<? super Animal> animals) {
animals.add(new Dog());

What happens?
Compiles and runs just fine.
void changeAnimals(List<?> animals) {
animals.add(new Dog());

What happens?
Compiler error. <?> generic wildcard is basically <? entends> and <? super> combined. You can't add to a collection using <?> for same reason you can't add with collection using <? extends>
Are the following the same or different?

<? extends Object>
Exactly identical.
Generic wildcards can be used in declations and instantiations.

T or F?
F. You can ONLY use in declaration.

Basically, the reference can say "I might be many types of thigns" but the actual instantiation of any object must say, "I am this specific thing".

List<? extends Animal> l = new ArrayList<Dog>();

List<Animal> = new ArrayList<? extends Dogs>();
What are the generic conventions <E> and <T>?
<E> stands for the generic-type of an element in a collection.
public interface List<E>{...}

<T> is the convention used to describe the generic type of things that are not or not exclusively the type of collection elements.
public class Rental<T> {}
class UseTwo<asdf, Y>{}


A parameterized generic type can be any legal java identifier.

You can have as many parameters as you like.
What are "bounds" in a generic class definition?
Works like wildcards but where you use ?, put your parametericzed generic type name.

class AnimalHolder<T extends Animal> {}
In a class declaration where you do not include a paramterized generic type (i.e. class Animal<T>) how would we add a method to the class that has a parameterized generic type?
Add a generic type parameter BEFORE the return type of the method.

class Fee{
public <T> void foo(T thing) {
List<T> l = new ArrayList<T>();

Can you add bounds on method generic type parameters?

public <T extends Animal> void fie(){}