Studydroid is shutting down on January 1st, 2019



keywords:
Bookmark and Share



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){} } Compiles?
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; } } Compiles?
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 transitive 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.
-Collection --Set ---SortedSet --List --Queue -Map --SortedMap
Name 13 concrete classes used in the collections framework.
<> HashSet LinkedHashSet <> TreeSet <> ArrayList Vector <> & <> LinkedList <> PriorityQueue <> Hashtable LinkedHashMap HashMap <> TreeMap Also utility classes that descend from Object and found in java.util: Collections Arrays (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?
ArrayList Vector 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?
Yes.
Sorted is ordering based on the value of the objects being considered. What are the 3 INHERENTLY SORTED concrete classes in the collections framework?
TreeMap TreeSet PriorityQueue
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. i.e. List lis = new ArrayList();
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(); al.add(""c""); al.add(""b""); al.add(""a""); System.out.println(al); Collections.sort(al); System.out.println(al); 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 { 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. Arrays.asList() 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?
hasNext() next()
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 i.e. Iterator it = listOfDogs.iterator(); (assumes listOfDogs is a List )
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).
MEMORIZE ALL THE KEY COLLECTION METHODS!
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.
x of y cards Next >|