0% found this document useful (0 votes)
0 views12 pages

Java Object Basics

The document provides comprehensive notes on Java's Object class, Collections, Lists, Sets, Maps, and advanced collection concepts. Key topics include methods like toString(), equals(), and hashCode(), as well as the differences between various collection types such as ArrayList, LinkedList, HashSet, and TreeSet. It also covers concurrency in collections and best practices for using different data structures.

Uploaded by

krishna das
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views12 pages

Java Object Basics

The document provides comprehensive notes on Java's Object class, Collections, Lists, Sets, Maps, and advanced collection concepts. Key topics include methods like toString(), equals(), and hashCode(), as well as the differences between various collection types such as ArrayList, LinkedList, HashSet, and TreeSet. It also covers concurrency in collections and best practices for using different data structures.

Uploaded by

krishna das
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Java Q&A Notes

Section 1: Object Class Basics

1. Object Class

• The parent of all classes in Java.


• Provides common methods like toString() , equals() , hashCode() , etc.

Object obj = new Object();

2. toString()

• Returns a string representation of the object.


• Default: className@hashCode.

class Student {
int id; String name;
public String toString(){
return id + " " + name;
}
}

3. equals()

• Compares two objects for equality.


• Default: checks memory address.
• Can be overridden for logical comparison.

s1.equals(s2); // compares values if overridden

4. hashCode()

• Returns an integer (hash) for the object.


• Used in HashMap/HashSet.

5. equals() & hashCode() relation

• If two objects are equal → they must have the same hashCode.
• Recommended to override both together.

6. clone()

• Creates a copy of an object.


• Throws CloneNotSupportedException if class doesn’t implement Cloneable .

1
7. finalize()

• Called by Garbage Collector before destroying object.

8. wait(), notify(), notifyAll()

• Used for thread communication.


• Must be inside synchronized block.

9. Why in Object class?

• Because every object can be locked for synchronization.

10. == vs equals()

• == : compares memory reference.


• equals() : compares values (if overridden).

11. Object vs Objects class

• Object : base class.


• Objects : utility class (null-safe methods like Objects.equals() ).

Section 2: Collection & Iterator Basics

12. Iterator vs Iterable

• Iterable: represents collection of elements (has iterator() method).


• Iterator: helps to traverse elements.

13. Why Collection extends Iterable?

• So every collection can be traversed easily.

14. Iteration using Iterator

Iterator<String> it = list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}

15. remove() in Iterator

• Removes last element returned by next() .

16. forEachRemaining()

• Performs action on remaining elements.

2
17. forEach() in Iterable

list.forEach(System.out::println);

18. spliterator()

• Used for parallel iteration.

19. contains() vs containsAll()

• contains(o) : checks single element.


• containsAll(c) : checks entire collection.

20. remove() vs removeAll()

• remove(o) : removes one element.


• removeAll(c) : removes all matching elements.

21. iterator() in Collection

• Returns Iterator to traverse.

22. Convert Collection to Array

Object[] arr = list.toArray();

23. removeIf()

• Removes elements based on condition.

24. retainAll()

• Keeps only common elements with given collection.

Section 3: List-related concepts

25. Array vs ArrayList

• Array: fixed size.


• ArrayList: dynamic size.

26. replaceAll()

• Replace each element using a function.

list.replaceAll(n -> n*2);

3
27. sort(Comparator c)

• Sorts list with custom comparator.

28. Make List empty

list.clear();

29. Enumeration vs Iterator vs ListIterator

• Enumeration: legacy, only forward.


• Iterator: forward, remove allowed.
• ListIterator: forward + backward.

30. Exceptions

• ConcurrentModificationException → modifying while iterating.


• NullPointerException → using null.
• UnsupportedOperationException → unmodifiable collection.
• IllegalArgumentException → invalid arguments.

31. subList()

• Returns a portion of list.

32. clear elements in range

list.subList(2, 5).clear();

33. List vs Set

• List: ordered, duplicates allowed.


• Set: unordered, no duplicates.

34. Marker Interfaces

• RandomAccess → fast access.


• Cloneable → allows clone().

35. ArrayList implementation

• Backed by dynamic array.

36. AbstractList vs ArrayList

• AbstractList: skeleton.
• ArrayList: concrete implementation.

37. trimToSize()

• Shrinks capacity to current size.

4
38. ensureCapacity()

• Expands capacity if needed.

39. ListIterator from ArrayList

ListIterator<String> it = list.listIterator();

40. Disadvantages

• Enumeration: read-only.
• Iterator: only forward.
• ListIterator: only for lists.

41. Ways to iterate List

• for loop, enhanced for, Iterator, ListIterator, forEach.

42. Ways to iterate Set

• for-each, Iterator, forEach.

43. Iterator methods

• hasNext() , next() , remove() , forEachRemaining()

44. ListIterator methods

• hasNext() , next() , hasPrevious() , previous() , add() , set()

45. Legacy collections

• Vector, Stack, Hashtable, Properties, Enumeration.

46. Vector vs ArrayList

• Vector: synchronized.
• ArrayList: not synchronized.

47. LinkedList implementation

• Doubly linked list.

48. ArrayList vs LinkedList

• ArrayList: fast random access.


• LinkedList: fast insertion/deletion.

5
Section 4: Set & Map related concepts

49. HashSet implementation

• Backed by HashMap.
• Stores elements in hash table.

50. TreeSet implementation

• Backed by TreeMap.
• Stores elements in sorted order.

51. LinkedHashSet implementation

• HashSet + LinkedList.
• Maintains insertion order.

52. HashSet vs TreeSet

• HashSet: unordered, faster.


• TreeSet: sorted, slower.

53. HashSet vs LinkedHashSet

• HashSet: no order.
• LinkedHashSet: maintains insertion order.

54. clone() in HashSet

• Shallow copy → elements not cloned.

55. Why Map doesn’t extend Collection?

• Collection works with single values.


• Map works with key-value pairs.

56. Advantage of Vector over ArrayList

• Vector is synchronized (thread-safe).

57. Why LinkedList extends AbstractSequentialList

• Because it provides sequential access, not random access.

Section 5: Advanced Map Concepts

58. Wildcards

• Used in Generics ( ? extends T , ? super T ).

6
59. Types of Cloning

• Shallow cloning.
• Deep cloning.

60. Internal Implementations

• ArrayList → Dynamic Array.


• LinkedList → Doubly Linked List.
• HashSet → HashMap.
• LinkedHashSet → HashMap + LinkedList.
• TreeSet → TreeMap.

61. Making ArrayList thread safe

• Collections.synchronizedList(list) .

62. LinkedHashMap vs Set

• LinkedHashMap: key-value pairs.


• Set: only values.

63. List hierarchy

• List → ArrayList, LinkedList, Vector.

64. Set hierarchy

• Set → HashSet, LinkedHashSet, TreeSet.

65. HashMap

• Key-value pair.
• Allows 1 null key, many null values.

66. List vs Set

• List: duplicates allowed.


• Set: no duplicates.

67. Comparator vs Comparable

• Comparable: natural order ( compareTo ).


• Comparator: custom order ( compare ).

68. HashSet vs TreeSet

• HashSet: faster, no order.


• TreeSet: slower, sorted.

69. ArrayList vs LinkedList

• ArrayList: fast read.


• LinkedList: fast insert/delete.

7
70. HashSet vs HashMap

• HashSet: only values.


• HashMap: key-value.

71. HashMap declaration

Map<Integer, String> map = new HashMap<>();

72. Hash codes

• Generated using object properties.


• Used in buckets.

73. Buckets in HashMap

• Each bucket stores entries with same hash.

74. Best collection for update

• LinkedList → if frequent insert/delete.


• ArrayList → if frequent read.

75. Best collection for fetch

• ArrayList (fast random access).

76. Features of ArrayList

• Dynamic, ordered, allows duplicates.

77. Best for sorting

• TreeSet, TreeMap, or sort ArrayList.

78. List description

• Ordered, duplicates allowed.

79. ArrayList vs Vector

• Vector: synchronized.
• ArrayList: faster.

80. Concurrent HashSet

• Implemented as CopyOnWriteArraySet .

81. Hashing mechanism

• Key → hash → bucket.

8
82. Iterator vs ListIterator

• Iterator: forward only.


• ListIterator: forward + backward.

83. HashSet vs TreeSet

• HashSet: O(1).
• TreeSet: O(log n).

84. Same keys in HashMap

• Replaces old value with new value.

85. Hash collisions

• Different keys → same hash.


• Resolved using LinkedList/Tree inside bucket.

Section 6: Map Advanced APIs

86. TreeSet vs TreeMap

• TreeSet: stores values.


• TreeMap: stores key-value.

87. containsKey vs containsValue

• Key: checks key.


• Value: checks value.

88. keySet()

• Returns all keys.

89. values()

• Returns all values.

90. entrySet()

• Returns key-value pairs.

91. Entry interface

• Used for Map.Entry to access key and value.

92. comparingByKey()

• Sort map entries by key.

9
93. comparingByValue()

• Sort map entries by value.

94. getOrDefault()

• Returns value if key exists, else default.

95. forEach(BiConsumer)

map.forEach((k,v) -> System.out.println(k+":"+v));

96. replaceAll()

• Replace each value using function.

97. put vs putIfAbsent

• put: replaces old.


• putIfAbsent: only if key not present.

98. Remove entry with condition

map.remove(key, value);

99. replace()

• replace(key, value) → replaces with new value.


• replace(key, oldValue, newValue) → conditional replace.

100. computeIfAbsent vs computeIfPresent

• IfAbsent: add new if missing.


• IfPresent: update if exists.

101. merge()

• Combine values for same key.

102. hashCode in HashSet/HashMap

• Called to find bucket.

103. hashCode in TreeSet/TreeMap

• Not used. They use compareTo() or Comparator.

104. TreeSet/TreeMap comparison

• Uses natural ordering or comparator.

10
105. Hashtable internal

• Hash table + synchronized.

106. HashMap vs Hashtable

• HashMap: not synchronized.


• Hashtable: synchronized.

107. TreeMap vs Hashtable

• TreeMap: sorted.
• Hashtable: unsorted.

108. Properties vs Hashtable

• Properties: for config (key & value are Strings).

109. Dictionary class

• Old class before Map.

110. EnumSet vs EnumMap

• EnumSet: Set for Enums.


• EnumMap: Map for Enums.

111. HashMap vs WeakHashMap

• WeakHashMap: keys can be garbage collected.

112. IdentityHashMap

• Uses == for key comparison.

113. Fail-fast vs Fail-safe

• Fail-fast: throws ConcurrentModificationException.


• Fail-safe: works on copy.

114. Concurrent collections

• ConcurrentHashMap, CopyOnWriteArrayList, CopyOnWriteArraySet, BlockingQueue.

115. HashMap vs ConcurrentHashMap

• HashMap: not thread safe.


• ConcurrentHashMap: thread safe.

116. CopyOnWriteArrayList vs CopyOnWriteArraySet

• Both are thread-safe, but one for List, one for Set.

11
117. Queue vs SynchronousQueue

• Queue: normal queue.


• SynchronousQueue: no storage, direct handoff.

118. Queue vs PriorityQueue

• PriorityQueue orders elements.

119. PriorityQueue internal

• Implemented as heap.

120. Hashtable vs ConcurrentHashMap

• Hashtable: synchronized, slow.


• ConcurrentHashMap: better concurrency.

121. How ConcurrentHashMap handles concurrency

• Divides into segments/buckets, locks only portion.

122. CopyOnWriteArrayList vs ArrayList

• CopyOnWrite: thread-safe, slower for write.


• ArrayList: faster, not thread-safe.

123. When to use CopyOnWriteArrayList

• When reads are frequent, writes are rare.

124. BlockingQueue usage

• For producer-consumer problems.


• Implementations: LinkedBlockingQueue, ArrayBlockingQueue.

✅ Completed all major Object, Collection, List, Set, Map, Concurrent Collection questions with
simple explanations and examples.

12

You might also like