Collections Flashcards

1
Q

boolean equals (Object obj)

A

Decides whether two objects are meaningfully

equivalent

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

void finalize()

A

Called by the garbage collector when the garbage

collector sees that the object cannot be referenced

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

int hashCode()

A

Returns a hashcode int value for an object
so that the object can be used in Collection
classes that use hashing, including Hashtable,
HashMap, and HashSet

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

final void notify()

A

Wakes up a thread that is waiting for this object’s

lock

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

final void notifyAll()

A

Wakes up all threads that are waiting for this

object’s lock

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

final void wait()

A

Causes the current thread to wait until another
thread calls notify() or notifyAll() on
this object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

String toString()

A

Returns a “text representation” of the object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What happens when you pass an

object reference to the System.out.println() method?

A

The object’s toString() method is called

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does System.out.println() print when you do not override toString()?

A
HardToRead@a47e0
It gives you the class name (at least that’s meaningful)
followed by the @ symbol, followed by the unsigned hexadecimal representation of the object’s hashcode.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How does == works by default?

A

Evaluates to true only when both references refer to the same object because == simply looks at the bits in the variable, and they’re either identical or they’re not.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What happens when you use collections if you do not override equals?

A

You can’t use an object as a hashtable key. Assume you put a Car object to hash with associated Person. Later you say give me the Person with Car X.But now you’re in trouble unless you still have a reference to the exact object you used as the key when you added it to the Collection. In other words, you can’t make an identical Car object and use it for the search.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q
Is this override valid;
class Foo { boolean equals(Object o) { } }
A

No. equals method is public in Object class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q
Is this override valid;
class Boo { public boolean equals(Boo b) { } }
A

When we look carefully we can see that it’s an overloading not overriding.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are the properties of equals method according to contract?

A

It is reflexive, symmetric, transitive, consistent. And for any non-null reference value x.equals(null) should return false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is being reflexive for equals contract?

A

For any reference value x, x.equals(x) should return true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is being symmetric for equals contract?

A

For any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is being transitive for equals contract?

A

For any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must
return true.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is being consistent for equals contract?

A

For any reference values x and y, multiple invocations of
x.equals(y) consistently return true or consistently return false, provided no information used in equals() comparisons on the object is modified.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Why is hashcode used for?

A

To increase the performance of large collections of data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How does hashing retrieval work?

A

1- Find right bucket using hashCode

2-Search the bucket for the right element using equals

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How does hashcode work for two equal objects?

A

If two objects are equal their hashcodes must be equal as well.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Is it legal to return same hashcode for all the objects?

A

Yes it is legal. It does not violate the contract but it is not efficient.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the contract for hashcode?

A
  • If two objects are equal according to equals they must return same hashcode.
  • During execution of a Java app. hashcode must return same value everytime, provided no info used in equals.
  • Two unequal objects can return same hashcode.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the problem with using transient in equals or hashcode implementation?

A

When an object is seralized, transient values are nor included. And when they are deserialized back, these values get default values. So the two instances are not same any more. Keep variables non-transient or, if they must be marked transient, don’t use them to determine hashcodes or equality.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What are the core interfaces in Collections API?

A

Collection, List, Queue, Set, Map, NavigableSet, SortedSet, SortedMap, NavigableMap

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What are the concrete implementation classes for Maps?

A

HashMap, Hashtable, TreeMap, LinkedHashMap - but they are not extended from Collection!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What are the concrete implementation classes for Sets?

A

HashSet, LinkedHashSet, TreeSet

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What are the concrete implementation classes for Lists?

A

ArrayList, Vector, LinkedList

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What are the concrete implementation classes for Queues?

A

PriorityQueue

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What are the concrete implementation classes for utilities?

A

Collections, Arrays

31
Q

What are the common methods in Collection interface?

A

add(), remove(), contains(), size(), iterator()

32
Q

What are the basic flavors is collections?

A
  • Lists of things Ordered, duplicates allowed, with an index
  • Sets of things May or may not be ordered and/or sorted; duplicates not allowed
  • Maps of things with keys May or may not be ordered and/or sorted; duplicate keys are not allowed
  • Queues of things to process Ordered by FIFO or by priority
33
Q

What are the subflavors for collections?

A

Sorted, Unsorted, Ordered, Unordered

34
Q

What is a natural order?

A

For Strings it’s the alphabetical order, for Integer objects its’ the numeric order. But for other objects there is no natural order unless one provided using interface Comparable. It is also possible to define different sort orders using Comparator interface.

35
Q

What is the basic property of List?

A

It cares about index. It has methods related to index like get, indexOf, add.

36
Q

Use of ArrayList

A

Use when you nedd fast iteration, also supports fast random access. But not good for a lot of insertion and deletion.

37
Q

What are the properties of Vector?

A

It is basically same with ArrayList but it’s synchronized. It is the only class that implement RandomAccess other than ArrayList.

38
Q

What are the properties of LinkedList?

A

Ordered by index position and elements are doubly linked to one another. Iteration is slow but has fast insertion and deletion. It also implements Queue interface so it supports methods like peek(), poll(), offer()

39
Q

What is the basic property of Set?

A

It cares about uniqueness - determined by equals().

40
Q

What are the properties of HashSet?

A

It’s unsorted and unordered. No duplicates allowed. Uses hashcode. When you iterate through, the order is unpredictable. When using that, the objects you add must override hashcode().

41
Q

Can a collection be sorted but unordered?

A

No. Sorting is a specific type of order which we call as sort order.

42
Q

What are the properties of LinkedHashSet?

A

Ordered version of HashSet. When iterated the order is the insertion order. When using that, the objects you add must override hashcode().

43
Q

What are the properties of TreeSet?

A

It is sorted. Uses red-black tree structure and guarantees that elements will be in ascending order according to natural order. Or you can give your own rule to constructor using Comparator interface.

44
Q

What is the basic property of Map?

A

It cares about unique keys. Like Sets they also rely on equals() method.

45
Q

What are the properties of HashMap?

A

Unordered and unsorted.Based on hashcode. Allows one null key and multiple null values.

46
Q

What are the properties of Hashtable?

A

Similar to HashMap but synchronized. You can’t have anything null - i.e. key or value.

47
Q

What are the properties of LinkedHashMap?

A

Maintains insertion order. Slower than HashMap for adding or removing but faster for iteration.

48
Q

What are the properties of TreeMap?

A

It is sorted by natural order of the elements. Lets you define a custom sort order using Comparator. Also implements NavigableMap.

49
Q

What are the properties of Queues?

A

Usually thought of as FIFO. Supports Collection methods for adding, removing and reviewing.

50
Q

What are the properties of PriorityQueue?

A

The main purpose is to create priority-in priority-out queue. Either by natural ordering or using Comparator.

51
Q

What happens in below code piece?
List myList = new ArrayList();
myList.add(42);

A

We are still adding an Integer object to myInts (not an int primitive); it’s just that autoboxing handles the wrapping for us.

52
Q

Is this a valid statement?
Integer y = new Integer(567);
y++;

A

Behind the scenes, the compiler does the unboxing and reassignment for you. Earlier, we mentioned that wrapper objects are immutable. What actually happened, however, is that a second wrapper object was created and its value was set to 568.

53
Q
What is the result of that code piece?
Integer y = 567; 
Integer x = y; 
System.out.println(y==x); 
y++;
System.out.println(x + " " + y); 
System.out.println(y==x);
A

true
567 568
false

54
Q

What is the output for that code piece?
Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println(“different objects”);
if(i1.equals(i2)) System.out.println(“meaningfully equal”);

A

different objects
meaningfully equal

The API developers decided that for all the wrapper classes, two objects are equal if they are of the same type and have the same value.

55
Q

What is the result for that:
Integer i3 = 10;
Integer i4 = 10;
if(i3 == i4) System.out.println(“same object”);
if(i3.equals(i4)) System.out.println(“meaningfully equal”);

A

same object
meaningfully equal

In order to save memory, two instances of the following wrapper objects (created through boxing) will always be == when their primitive values are the same:

  • Boolean
  • Byte
  • Character from \u0000 to \u007f (7f is 127 in decimal)
  • Short and Integer from –128 to 127
56
Q

What happens when == is used to compare a primitive to a wrapper?

A

When == is used to compare a primitive to a wrapper, the wrapper will be unwrapped and the comparison will be primitive to primitive.

57
Q
Which of those declarations are legal?
ArrayList stuff = new ArrayList<>();
List myDogs = new ArrayList<>();
Map dogMap = new HashMap<>();
List<> stuff = new ArrayList();
A

All except the last. Diamond can not be used on left side of the operation.

58
Q

How can we sort an ArrayList?

A

Using Collections.sort(stuff);

Collections.sort() & Arrays.sort() uses can sort classes that implement Comparable

59
Q

How is Comparable implemented?

A

A class must implement a single method; compareTo()

60
Q

How does compareTo() method works?

A

returns;

  • Negative If thisObject < anotherObject
  • Zero If thisObject == anotherObject
  • Positive If thisObject > anotherObject
61
Q

What is the drawback of implementing Comparable?

A

It can be implemented once for a class. And we have to modify the class that we want to sort to implement compareTo()

62
Q

What’s a better alternative for Comparable?

A
There is an overloaded version of sort which takes Comparator as argument. It only has one method; compare()
import java.util.*;
class GenreSort implements Comparator {
    public int compare(DVDInfo one, DVDInfo two) {
        return one.getGenre().compareTo(two.getGenre());
    }
}
63
Q

What are the properties of Collections.sort() and Arrays.sort()?

A

They are static methods and they modify the object they are sorting, they do not return a new instance.

64
Q

How is searching performed with Collections and Arrays?

A

Using binarySearch()

65
Q

How can we convert a List/Set to an array?

A

The List and Set classes have toArray() methods.

66
Q

How can we convert an array to a list?

A

Arrays.asList() copies an array into List and the list and the array are joined. A change in one of them changes the other as well.

67
Q

How does List.toArray() works?

A

toArray() returns an object array and toArray(T[] a) returns a list of T.

68
Q

What is an Iterator?

A

It’s an object that’s associated with a specific collection. It lets you loop through the collection step by step. It has two important methods;

  • boolean hasNext()
  • Object next()
69
Q

What property do elements of a collection to be sorted?

A

Whenever you want a collection to be sorted, its elements must be mutually comparable. Remember that unless otherwise specified, objects of different types are not mutually comparable.

70
Q

What property should a class have in order to be used in a Hash?

A

It should be overriding equals() and hashCode()—syf 625

71
Q

What are the methods if PriorityQueue?

A

offer() -add an element to queue
peek()- returns element with highest priority without removing
poll() - returns highest priority element and removes it

72
Q
String[] sa = {">ff ff FF pq3 = new PriorityQueue();
for(String s : sa)
pq3.offer(s);
for(String s : sa)
System.out.print(pq3.poll() + " ");

What’s the result?

A

This produces
> f< >FF< >f < >ff<
If you remember that spaces sort before characters and that uppercase letters sort before lowercase characters, you should be good to go for the exam.

73
Q

Key attributes of common collection classes

A
  • ArrayList Fast iteration and fast random access.
  • Vector It’s like a slower ArrayList, but it has synchronized methods.
  • LinkedList Good for adding elements to the ends, i.e., stacks and queues.
  • HashSet Fast access, assures no duplicates, provides no ordering.
  • LinkedHashSet No duplicates; iterates by insertion order.
  • TreeSet No duplicates; iterates in sorted order.
  • HashMap Fastest updates (key/values); allows one null key, many null values.
  • Hashtable Like a slower HashMap (as with Vector, due to its synchronized methods). No null values or null keys allowed.
  • LinkedHashMap Faster iterations; iterates by insertion order or last accessed; allows one null key, many null values.
  • TreeMap A sorted map.
  • PriorityQueue A to-do list ordered by the elements’ priority.