Java Collections Framework

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Consider a scenario where a custom class Event does not override the equals() method. If multiple Event objects with identical attribute values are added to a HashSet, what behavior would be observed, and how does this contrast with the intended behavior of a Set?

  • Multiple `Event` objects will be added to the `HashSet`, as each object will have a unique hash code based on its memory address. (correct)
  • Only one `Event` object will be added, and subsequent attempts to add identical objects will silently fail without modifying the `HashSet`.
  • Only one `Event` object will be added to the `HashSet`, as `HashSet` relies on reference equality by default.
  • Multiple `Event` objects will be added to the `HashSet`, but adding a duplicate object will throw an `IllegalArgumentException`.

In the context of the Java Collections Framework, if you are tasked with designing a highly concurrent system where multiple threads frequently access and modify a map, which implementation would offer the best trade-off between thread safety and performance, assuming minimal locking overhead is paramount?

  • `ConcurrentHashMap` with a high concurrency level and lock striping to reduce contention among threads. (correct)
  • `ConcurrentHashMap` with a low concurrency level to minimize memory footprint and synchronization costs.
  • `Collections.synchronizedMap(new HashMap<>())` for simplicity and ease of implementation.
  • `Hashtable` to leverage its inherent synchronization mechanisms despite potential bottlenecks.

Given a scenario where you need to store elements in a collection that must maintain insertion order and allow duplicates, but you also require the ability to efficiently retrieve elements based on their insertion index. Which combination of Java Collection interfaces and implementations would best satisfy these requirements, considering both memory usage and access time complexity?

  • `Set` interface implemented by `LinkedHashSet`, ensuring uniqueness while maintaining insertion order.
  • `List` interface implemented by `LinkedList`, as it offers efficient insertion and deletion at both ends and maintains insertion order.
  • `Queue` interface implemented by `LinkedList`, because queue allows duplicates.
  • `List` interface implemented by `ArrayList`, as it provides constant-time access to elements by index and preserves insertion order. (correct)

Consider a scenario where you have a large dataset of custom objects, and you need to perform frequent range queries (e.g., find all objects with a property value between X and Y). Which data structure would be most appropriate to optimize the performance of these range queries, assuming the objects are not inherently comparable and memory usage is a secondary concern?

<p>A <code>TreeMap</code> that utilizes a custom <code>Comparator</code> to define the ordering of objects based on the property used in range queries. (B)</p> Signup and view all the answers

You are designing a real-time stock trading system that requires maintaining a constantly updated, sorted list of trade orders. Given the high frequency of order insertions and deletions, which List implementation would be most suitable to minimize latency and ensure optimal throughput?

<p>A custom lock-free <code>List</code> implementation using atomic operations and concurrent data structures. (D)</p> Signup and view all the answers

Consider a scenario where you are tasked with implementing a custom caching mechanism. You need to ensure that the cache evicts the least recently used (LRU) entries when it reaches its maximum capacity. Which combination of data structures would be most appropriate to achieve this efficiently?

<p>A <code>LinkedHashMap</code> configured with access-order true to maintain the LRU order. (D)</p> Signup and view all the answers

In a distributed microservices architecture, you need to implement a mechanism for aggregating data from multiple services while ensuring that the aggregated result contains only unique entries and is sorted based on a custom business logic. Which approach would provide the most performant and scalable solution, leveraging the Java Collections Framework?

<p>Employ a <code>ConcurrentSkipListSet</code> with a custom <code>Comparator</code> to allow concurrent insertion of data from multiple services while maintaining uniqueness and sorting. (C)</p> Signup and view all the answers

Given a scenario where you have a large number of objects with a high degree of inter-dependencies, and you need to efficiently determine the transitive closure of a particular object (i.e., all objects reachable from it through the dependencies). Which combination of data structures and algorithms would be most appropriate to minimize computational complexity?

<p>Represent the dependencies as an adjacency list and use depth-first search (DFS) to traverse the graph iteratively, storing visited nodes in a <code>HashSet</code>. (A)</p> Signup and view all the answers

In the context of Java's Iterable interface and the enhanced for-each loop, what are the implications of modifying a collection directly (e.g., adding or removing elements) while iterating over it using the for-each loop? Specifically, which collection types and modification patterns are most likely to result in a ConcurrentModificationException, and why?

<p><code>ArrayList</code> and <code>HashSet</code> are particularly susceptible to <code>ConcurrentModificationException</code> due to their fail-fast iterators, which detect structural modifications made outside the iterator. (B)</p> Signup and view all the answers

Consider a scenario where you are implementing a custom data structure that requires efficient retrieval of elements based on multiple criteria (e.g., querying employees based on department and salary range). Which approach would provide the most optimized solution, minimizing both space and time complexity?

<p>Employing a combination of <code>HashMap</code> for primary key lookup and secondary indexes (e.g., <code>TreeMap</code> or <code>SortedSet</code>) for each criterion. (D)</p> Signup and view all the answers

Given the code snippet:

List<Integer> lst = new LinkedList<>();
lst.add(10);
lst.add(11);
lst.add(13);
lst.add(20);
int count = 0;
for (Iterator<?> itr = lst.iterator(); itr.hasNext(); ) {
    itr.next();
    if (count == 1)
        lst.remove(count); // Line X
    count++;
}

What is the most likely outcome when Line X is executed?

<p>The code will throw a <code>ConcurrentModificationException</code> because the list is modified while iterating over it. (A)</p> Signup and view all the answers

Considering the following code snippet:

List<Integer> lst = new LinkedList<>();
lst.add(10);
lst.add(11);
lst.add(13);
lst.add(20);
int count = 0;
for (ListIterator<Integer> itr = lst.listIterator(); itr.hasNext(); ) {
    itr.next();
    if (count == 2)
        itr.add(22); // Line X
    count++;
}

What will be the state of lst after executing Line X?

<p><code>lst</code> will be <code>[10, 11, 22, 13, 20]</code>. (C)</p> Signup and view all the answers

Which of the following statements accurately describes the contract and behavior of the Set interface in Java's Collections Framework, especially concerning object equality?

<p>A <code>Set</code> enforces uniqueness by invoking the <code>equals()</code> method on each element. If two elements are considered equal by <code>equals()</code>, only one of them will be added to the <code>Set</code>. (C)</p> Signup and view all the answers

In the realm of Java's Optional class, what are the nuanced differences in behavior and use cases between Optional.of(T value), Optional.ofNullable(T value), and Optional.empty()?

<p><code>Optional.of(T value)</code> creates an <code>Optional</code> instance assuming that the value is non-null, otherwise it throws a <code>NullPointerException</code>. <code>Optional.ofNullable(T value)</code> creates an <code>Optional</code> that can hold a null reference and <code>Optional.empty()</code> creates an empty <code>Optional</code>. (A)</p> Signup and view all the answers

Given a large dataset of time-series data where each data point is associated with a timestamp, and considering the need for efficient retrieval of data points within specific time ranges, which data structure would be most suitable to balance memory usage and query performance?

<p>A <code>TreeMap</code> using the timestamp as the key, allowing for efficient range queries in $O(log \space n)$ time, but with higher memory overhead compared to a <code>HashMap</code>. (C)</p> Signup and view all the answers

Assuming you have implemented a custom hashCode() method for a class representing complex numbers. What are the implications if the generated hash codes are not uniformly distributed across the entire range of possible integer values?

<p>A non-uniform distribution of hash codes will inevitably lead to a higher frequency of collisions in hash-based collections, degrading performance and potentially causing worst-case $O(n)$ behavior. (B)</p> Signup and view all the answers

What are the key differences in memory management and performance characteristics between ArrayList and LinkedList when dealing with extremely large datasets (millions of elements), especially when considering memory fragmentation and cache locality?

<p><code>ArrayList</code> can suffer from memory fragmentation as it requires contiguous memory blocks, while <code>LinkedList</code> avoids this issue by allocating memory for each node separately, at the expense of cache locality. (B)</p> Signup and view all the answers

When deciding between using a TreeSet and a HashSet for storing a large collection of custom objects that require uniqueness, what factors should be considered regarding memory footprint and algorithmic complexity, assuming that the objects do not intrinsically implement Comparable?

<p><code>HashSet</code> generally consumes less memory due to its simpler structure, while <code>TreeSet</code> requires additional memory for maintaining its sorted order, which is crucial for efficient retrieval. To allow <code>TreeSet</code> to function, a <code>Comparator</code> must be provided. (B)</p> Signup and view all the answers

Given a scenario where you need to implement a custom thread-safe queue with non-blocking operations for high-throughput message processing, which implementation of the Queue interface would be most appropriate, considering both performance and memory usage?

<p><code>ConcurrentLinkedQueue</code> which provides non-blocking, thread-safe operations with minimal overhead. (A)</p> Signup and view all the answers

In the context of Java garbage collection and memory management, what are the potential implications of using very large ArrayList instances that are frequently resized, especially in terms of triggering full GC cycles?

<p>Frequent resizing can lead to memory fragmentation and increased allocation pressure, potentially triggering more frequent full GC cycles and impacting application performance. (C)</p> Signup and view all the answers

Consider the scenario where you want to implement a dictionary using Map to store student names and their corresponding grades. Which implementation would be most appropriate if you need the stored entries to be sorted reverse alphabetically by student name?

<p><code>TreeMap</code> with a custom <code>Comparator</code> implementing reverse alphabetical order. (D)</p> Signup and view all the answers

Given a collection of a very large number of objects, what technique will minimize both the memory footprint and improve performance? Implementations include HashMap, TreeMap, WeakHashMap, and EnumMap.

<p>Use an <code>EnumMap</code> keyed by the enum representation if the number of keys is fixed and known, and map the large objects to their corresponding enum, due to faster performance and tightly packed approach. (D)</p> Signup and view all the answers

In a system designed to efficiently process a large stream of network packets in real-time, each packet needs to be timestamped and processed in the order of arrival. What data structure guarantees the order and makes this possible, but also minimizes the blocking between inserting new packets from network interfaces and processing them by worker threads?

<p>A <code>ConcurrentLinkedQueue</code>. (A)</p> Signup and view all the answers

Given a multi-threaded application that frequently accesses a shared collection, and the collection needs to be traversed and updated. Which of the following techniques should be implemented to prevent ConcurrentModificationException while ensuring the integrity of the data?

<p>Use <code>CopyOnWriteArrayList</code> for frequent read and infrequent modification operations to avoid any iterator-based exceptions. (C)</p> Signup and view all the answers

Flashcards

Interfaces (in Collections Framework)

Interfaces are Abstract Data Types (ADTs) that define a contract for implementations.

Implementations (of ADT)

Implementations are concrete classes providing specific ways to realize ADTs.

Algorithms (Collections Framework)

The Collections Framework provides built-in methods like sorting to manipulate collections.

java.util package

The Collections Framework is available through this Java package.

Signup and view all the flashcards

Java 5 and Generic Types

The Collections Framework originally used 'Object' before Java 5 introduced generics.

Signup and view all the flashcards

What is a Collection?

A grouping of elements, which may or may not be ordered or contain duplicates.

Signup and view all the flashcards

Collection constructors: C() and C(Collection c)

Classes implementing Collection must provide these constructors.

Signup and view all the flashcards

Collection Interface Methods

The basic methods size(), isEmpty(), contains(), add(), remove(), clear(), toArray(), and iterator()

Signup and view all the flashcards

List

This type of list can contain duplicate elements & preserves insertion order.

Signup and view all the flashcards

List Interface Methods

The methods add (index, element), get(index), set (index, element), and remove(index).

Signup and view all the flashcards

List Implementations

Common implementations include ArrayList and LinkedList.

Signup and view all the flashcards

Queue Interface

An interface for collections inserted using FIFO or priority.

Signup and view all the flashcards

Set Interface

A collection that doesn't allow adding duplicate elements.

Signup and view all the flashcards

SortedSet characteristics

Elements are traversed in ascending order according to their natural ordering.

Signup and view all the flashcards

Set Implementations

HashSet implements Set using Hash Tables. LinkedHashSet extends HashSet, maintaining insertion order. TreeSet implements SortedSet using R-B trees.

Signup and view all the flashcards

Iterator

A method to traverse the elements of a collection.

Signup and view all the flashcards

Iterable interface

Iterable interface provides iterator() method for iterating.

Signup and view all the flashcards

Iterator methods

The iterator methods are hasNext(), next(), and remove().

Signup and view all the flashcards

Concurrent Modification

It is unsafe to modify collections while iterating, unless using iterator's methods.

Signup and view all the flashcards

Map

A kind of container that associates keys to values; keys must be unique.

Signup and view all the flashcards

Map Interface Methods

These are operations such as put(K key, V value), get(K key), remove(K key), containsKey(K key).

Signup and view all the flashcards

SortedMap Interface

This interface traverses elements according to the keys' natural ordering.

Signup and view all the flashcards

Map Implementations

HashMap implements Map with no order. LinkedHashMap extends HashMap preserving insertion order. TreeMap implements SortedMap with ascending key order.

Signup and view all the flashcards

Optional Class

A class used to make explicit that a return value may be missing.

Signup and view all the flashcards

Optional Methods

An access to embedded value of Optional through isPresent(), ifPresent(), get(), orElse(), orElse().

Signup and view all the flashcards

Optional Creation

Static factory methods such as of(T v), ofNullable(T v), and empty()

Signup and view all the flashcards

General Interfaces

Using general interfaces makes future changes more flexible.

Signup and view all the flashcards

Selecting Container Types

Use a Map if access by key is needed; otherwise, use a Collection.

Signup and view all the flashcards

Efficiency

Time and space complexity measures algorithms as element number changes.

Signup and view all the flashcards

Time Complexity

Constant is independent of n, Logarithmic grows as log(n), Linear grows proportionally to n, Loglinear grows as n log(n), Quadratic grows proportionally to n^2.

Signup and view all the flashcards

List Implementation Efficiencies

In ArrayList, get(n) will be constant, add(0, ...) will be linear, add() will be constant. In LinkedList, get(n) will be linear, add(0, ...) will be constant, add() will be constant.

Signup and view all the flashcards

java.util.Collections Algorithms

Algorithms are static methods of java.util.Collections, and include operations like sort(), binarySearch(), shuffle(), reverse(), rotate(), min(), and max().

Signup and view all the flashcards

What does the sort() method operate on?

Work on List since it has the concept of position.

Signup and view all the flashcards

Collections Framework

The collection framework is structured by interfaces and classes for containers, which includes grounp containers and associative containers.

Signup and view all the flashcards

ListIterator and Iterator own methods

These help avoid the unsafe iteration of collections while modifying

Signup and view all the flashcards

Map

This is a way of having a container of associating each key to a certain value

Signup and view all the flashcards

SortedMap

These have their elements are traversed according to the keys' natural ordering

Signup and view all the flashcards

Optional class

Represents a class that is used to represent a potential value

Signup and view all the flashcards

T orElse(T default)

These will give you a certain value if it's presnet, otherwise it will return the default

Signup and view all the flashcards

Study Notes

  • Java Collections Framework is part of object-oriented programming. The material is version 4.2.0, dated 2023, by Maurizio Morisio and Marco Torchiano.

Collections Framework

  • Includes interfaces, which are Abstract Data Types (ADTs).
  • Includes Implementations that are concrete versions of the ADTs
  • Uses Algorithms to manipulate the collections, like sorting
  • Found in the java.util package.
  • Originally used Object type, but Java 5 introduced generic types for more specific type handling.

Interfaces

  • Defines different container types in the framework.
  • Iterable is at the top of the hierarchy.
  • Collection extends Iterable and is the base for group containers.
  • Set, Queue and List extend Collection.
  • SortedSet extends Set.
  • Map is for associative containers.
  • SortedMap extends Map.

Implementations

  • Shows how the interfaces are implemented by concrete classes.
  • HashSet, LinkedHashSet, and TreeSet implement the Set interface.
  • LinkedList and PriorityQueue implement the Queue interface.
  • LinkedList and ArrayList implement the List interface.
  • HashMap, LinkedHashMap, and TreeMap implement the Map interface.

Internals

  • Highlights the data structures used by various collection implementations.
  • HashSet uses a hash table.
  • TreeSet employs a balanced tree.
  • ArrayList utilizes a resizable array.
  • LinkedList uses a linked list.
  • LinkedHashSet combines a hash table with a linked list (HT + LL).
  • HashMap uses a hash table.
  • TreeMap uses a balanced tree.
  • LinkedHashMap combines a hash table with a linked list.

Collection

  • Represents a group of elements as references to objects.
  • The elements may or may not be ordered or duplicated, based on the specific Collection implementation.
  • Implements the Iterable interface.
  • Classes should provide two constructors: a default constructor C() and a constructor accepting another Collection instance C(Collection c).

Collection Interface

  • size(): Returns the number of elements.
  • isEmpty(): Checks if the collection is empty.
  • contains(E element): Checks if an element exists.
  • containsAll(Collection<?> c): Checks if all elements from another collection exist.
  • add(E element): Adds an element.
  • addAll(Collection<? extends E> c): Adds all elements from another collection.
  • remove(E element): Removes an element.
  • removeAll(Collection<?> c): Removes all elements from another collection.
  • clear(): Removes all elements.
  • toArray(): Returns an array containing all elements.
  • iterator(): Returns an iterator for the collection.

List

  • Can contain duplicate elements.
  • Preserves the insertion order of elements.
  • Allows the user to define the insertion point using an index.
  • Elements can be accessed by their position.
  • Extends the Collection interface.

List Interface

  • get(int index): Retrieves the element at the specified index.
  • set(int index, E element): Replaces the element at the specified index with the specified element.
  • add(int index, E element): Inserts the specified element at the specified index.
  • remove(int index): Removes the element at the specified index.
  • addAll(int index, Collection c): Inserts all of the elements in the specified collection into this list, starting at the specified position.
  • indexOf(E o): Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
  • lastIndexOf(E o): Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
  • subList(int from, int to): Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

List Implementations

ArrayList

  • ArrayList(): Constructs an empty list with an initial capacity of ten.
  • ArrayList(int initialCapacity): Constructs an empty list with the specified initial capacity.
  • ArrayList(Collection c): Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
  • ensureCapacity(int minCapacity): Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.

LinkedList

  • addFirst(E o): Inserts the specified element at the beginning of this list.
  • addLast(E o): Appends the specified element to the end of this list.
  • getFirst(): Returns the first element in this list.
  • getLast(): Returns the last element in this list.
  • removeFirst(): Removes and returns the first element from this list.
  • removeLast(): Removes and returns the last element from this list.

Queue Interface

  • A Collection designed for holding elements prior to processing.
  • Inserts elements using either Insertion order (FIFO) or Element natural order (Priority queue):
  • Defines a head position where the first element can be accessed.
  • peek(): Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
  • poll(): Retrieves and removes the head of this queue, or returns null if this queue is empty.

Queue Implementations

LinkedList

  • head is the first element of the list.
  • FIFO: First-In-First-Out.

PriorityQueue

  • head is the smallest element based on natural ordering or comparator.

Set Interface

  • Contains no methods beyond those inherited from Collection.
  • add() has the restriction that no duplicate elements are allowed where e1.equals(e2) == false ∀ e1,e2 ∈ Σ
  • Elements are traversed by the Iterator in no particular order.

SortedSet Interface

  • Contains no duplicate elements.
  • The Iterator traverses elements according to the natural ordering (ascending).
  • Augments the Set interface with methods:
    • first(): Returns the first (lowest) element currently in this sorted set.
    • last(): Returns the last (highest) element currently in this sorted set.
    • headSet(E toElement): Returns a view of the portion of this sorted set whose elements are strictly less than toElement.
    • tailSet(E fromElement): Returns a view of the portion of this sorted set whose elements are greater than or equal to fromElement.
    • subSet(E from, E to): Returns a view of the portion of this sorted set whose elements range from fromElement, inclusive, to toElement, exclusive.

Set Implementations

HashSet

  • Implements the Set interface.
  • Uses hash tables as its internal data structure which are faster.

LinkedHashSet

  • Extends HashSet.
  • Elements are traversed by the iterator according to the insertion order.

TreeSet

  • Implements the SortedSet interface.
  • Uses R-B trees as its internal data structure, which is computationally expensive.

Note on Sorted Collections

  • Different constructors require different implementations of custom ordering.

TreeSet()

  • Requires natural ordering, meaning elements must implement the Comparable interface.

TreeSet(Comparator c)

  • Ordering follows the comparator rules instead of natural ordering.

Iterators

  • Iterable interface: Container of elements that can be iterated upon. -Provides a single instance method: Iterator iterator(). -Returns the iterator on the elements of the collection. -Collection extends Iterable.

Iterators and Iteration

  • Iterating over elements is a common operation with collections.
  • The Iterator interface offers a transparent way to cycle through all elements of a Collection.
  • Keeps track of last visited element of the related collection.
  • Each time the current element is queried, it moves on automatically.

Iterator

  • Permits iteration on the elements of a collection.
  • Has two main methods:
    • hasNext(): Checks if there is a next element to iterate on.
    • next(): Returns the next element and advances one position.
    • remove(): Optional to remove the current element, from the collection

Iterable forEach

  • Default method defined by the Iterable interface.
  • Can be used to perform operations on elements with a functional interface: forEach(Consumer<? super T> action).

Note Well on Iterators

  • It is unsafe to iterate over a collection you are modifying (add/remove) at the same time.
  • Unless you are using the iterator's own methods:
    • Iterator.remove()
    • ListIterator.add()

Maps

  • Stores entries in key/value pairs.
  • Keys must be unique and objects.
  • Values must be objects.

Map Interface Methods

  • put(K key, V value): Associates the specified value with the specified key in this map.
  • get(K key): Returns the value to which the specified key ismapped, or null if this map contains no mapping for the key.
  • remove(K key):Removes the mapping for the specified key from this map if present.
  • containsKey(K key): Returns true if this map contains a mapping for the specified key.
  • containsValue(V value): Returns true if this map maps one or more keys to the specified value.
  • keySet(): Returns a Set view of the keys contained in this map.
  • values(): Returns a Collection view of the values contained in this map.
  • size(): Returns the number of key-value mappings in this map.
  • isEmpty(): Returns true if this map contains no key-value mappings.
  • clear(): Removes all of the mappings from this map.

SortedMap Interface

  • Elements are traversed by the natural ordering of the keys or by comparator passed to constructor. Methods exist to augment Map
    • SortedMap subMap(K fromKey, K toKey): Returns a view of the portion of this sorted map whose keys range from fromKey, inclusive, to toKey, exclusive.
    • SortedMap headMap(K toKey) : Returns a view of the portion of this sorted map whose keys are strictly less than toKey.
    • SortedMap tailMap(K fromKey) : Returns a view of the portion of this sorted map whose keys are greater than or equal to fromKey.
    • K firstKey(): Returns the first (lowest) key currently in this sorted map.
    • K lastKey(): Returns the last (highest) key currently in this sorted map.

Map Implementations

  • Similar to Set

HashMap

-Implements Map -No order

LinkedHashMap

-Extends HashMap -Insertion Order

TreeMap

-Implements SortedMap -Ascending key order

Optional

  • Class used to contain potential values.
  • Used to return what may be missing.

Optional<T>

  • Access to embedded value with the following -boolean isPresent() = checks if the Optional has value -IfPresent(Consumer<?T> block) = executes given code if value is present -T get() = returns the value if present, otherwise, NoSuchElementException is thrown -T orElse(T default) = returns default if value isn't present -TorElse(Supplier)` = if empty, it returns the value of s

Creating Optinal<T> Objects

  • Using the static factory objects to creates the base objects -of(T v) = throws exception if v is null -ofNullable(T v) = returns and empty OPTIONAL, if v is null -empty() = returns an empty OPTIONAL

Using Collection

  • When using a collection, use general collections in order to increase flexibility -For example 'List' is an acceptable general term, where 'LinkedList' is not
  • Using common language while coding increase 'thinking' -Think first about what a container can do -Think later about how the function will be stored

Selecting Container Types

  • When selecting container types, follow the below: -Key Access = Map -Value Types = SortedMap If map is not a viable option, then review COLLETION -Index Access = List -Class depeneds on the expected operation If not a Viable option, then review Queue. -Otherwise, if a no duplicate, use Set -If Elements are sorted, use SortedSet.

Efficiency

  • When referring to time and space complexity, compute using elements using big-O terminology. -Constant n = does not impact element -Logrithimic = log(n) impact value -Linear = proportionally to size of n -Loglinear = n*log(n) value -Quadratic = n^2 proportionally impacts value

Differences in List Implementation

ArrayList

  • get(n) -Constant
  • add(0, ...) -Linear
  • add() -Constant

LinkedList

  • get(n) -Linear
  • add(0, ...) -Constant
  • add() -Constant

Hashmap

  • Hashmaps takes constant time for get/put command (on no collisions)
  • Automic reallocation on load balance reached Constructor optional values -Load factor - defualt 0.75 -Intitial Capacity = default of 16

Hash Implementation

  • Hash based implementation of HashMap AND HashSet work by defining a suitable 'hashCode()'' method
  • With the following spread rule -value should be value
  • collisions can occur when the following fails -when two entries fall in the same bucket -if issues continue 'chaining' will be used to push to the list -overall, reduced time impacts efficency

TreeMap

  • implements Red-Black Tree algorithim - Log(n) -maintain and transverse in correct order -key must be sortable with Comparable or Comparator algorithms

Limitations To Tree

  • require comparable entries with natural orders if TreeMap and TreeSet are to be used -Comparator to sort Entries
  • TreeMap maintains keys to maintain the value's return -returned values via sorted keys

search efficency

  • 100k searches require the follwoing times for containers: ArrayList - 40s HashMap - 3ms LinkedList - 1 Hour Treemap - 60ms

Algorithms

  • Static methods of the java.util.Collections class -Works on only on list, since it concepts order of position. -sort() = merges list & nlog(n) -binarySearch = searches ordered sequences
  • shuffle() = unsorts the sequence -reverse() = reverses the ordered sequences -rotate() = rotates given distance -min() and max() = collection types

Sort() Method

  • Operates on List with need access by sort index -Uses two variables

  • <T extends Comparable<? super T>> void sort(List<T> list)

  • <T> void sort(List<T> list, Comparator<? super T> cmp) </T></T>

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Java Programming: Collections and Data Structures
10 questions
Java Collections Framework
8 questions

Java Collections Framework

GroundbreakingLimerick avatar
GroundbreakingLimerick
Java Data Structures
38 questions

Java Data Structures

ConsiderateHydrangea2185 avatar
ConsiderateHydrangea2185
Java Collections Framework
35 questions
Use Quizgecko on...
Browser
Browser