[go: up one dir, main page]

0% found this document useful (0 votes)
4 views9 pages

Assignment Test 1 Questions and Answers

The document is an assignment test covering Java Collections Framework, including ArrayList, LinkedList, HashSet, and HashMap. It includes theoretical questions on their properties, performance, and manipulation, as well as programming examples demonstrating their usage. The test is divided into theory (4 marks) and programming (6 marks) sections.
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)
4 views9 pages

Assignment Test 1 Questions and Answers

The document is an assignment test covering Java Collections Framework, including ArrayList, LinkedList, HashSet, and HashMap. It includes theoretical questions on their properties, performance, and manipulation, as well as programming examples demonstrating their usage. The test is divided into theory (4 marks) and programming (6 marks) sections.
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/ 9

Assignment Test I

Marks : 10 marks
Theory : 4 marks ; Programming : 6 marks

Theory Questions

ArrayList

Basic Understanding:

What is an ArrayList in Java? How does it differ from an array?

An ArrayList is a resizable array implementation of the List interface. Unlike arrays, ArrayLists can
grow and shrink in size. They are part of the java.util package.

What is the time complexity of adding an element to an ArrayList? What about getting an element?

Adding an element to the end of an ArrayList is O(1) on average (amortized), but can be O(n) if
resizing occurs. Accessing an element is O(1).

Performance:

When would you choose an ArrayList over an array? What are the advantages?

You would choose an ArrayList over an array when you need dynamic resizing, easy insertion and
deletion, or additional helpful methods.

What are potential drawbacks of using an ArrayList in terms of performance?


Drawbacks include slower removals from the middle and lack of thread safety.

Manipulation:

How do you remove an element from an ArrayList?


To remove an element, use remove(Object o) or remove(int index).

What happens if you try to remove an element that does not exist?
If the element does not exist, remove(Object o) returns false.

Describe how you would sort an ArrayList of strings.


Use Collections.sort(yourArrayList) to sort an ArrayList of strings.

Capacity Management:

What is the initial capacity of an ArrayList, and how does it grow?


The initial capacity of an ArrayList is 10 if not specified. It doubles its size when it needs to grow.
Explain the concept of "shrinkage" in ArrayList.
"Shrinkage" reduces the size of the underlying array if excessively unused, but this isn't an automatic
behavior.

Thread Safety:

Is ArrayList thread-safe? If not, how can you make it safe for use in a multi-threaded environment?

ArrayList is not thread-safe. To make it thread-safe, you can use Collections.synchronizedList(new


ArrayList<>()).

LinkedList

Basic Understanding:

What is a LinkedList, and how does it differ from an ArrayList?

A LinkedList is a doubly-linked list implementation of the List interface. It allows node insertion and
deletion without resizing.

Can you explain the difference between a singly linked list and a doubly linked list?

A singly linked list only has pointers to the next node, while a doubly linked list has pointers to both
previous and next nodes.

Performance:

What are the time complexities for adding and removing elements in a LinkedList compared to
ArrayList?

Adding/removing elements at the ends (head/tail) is O(1), while accessing elements is O(n) (linear
time).

In what scenarios would you prefer using a LinkedList over an ArrayList?


Prefer a LinkedList when you need frequent insertions/deletions from the list.

Manipulation:

How do you implement a queue using a LinkedList in Java?

To implement a queue, use add(), remove(), and peek() methods on the LinkedList.

Describe how to reverse a LinkedList in place.


To reverse a LinkedList, you can iterate through it and change the next pointers, or use a stack to store
nodes and re-link them.

Traversal:

How would you traverse a LinkedList?


Traverse using a for-each loop or an Iterator.

Can you implement a method to find the middle element of a LinkedList efficiently?

To find the middle element, use two pointers: move one pointer by one step and another by two steps.
When the fast pointer reaches the end, the slow pointer will be at the middle.

Memory Considerations:

Discuss the memory overhead involved in using a LinkedList compared to an ArrayList.


A LinkedList has a higher memory overhead due to the additional pointers for each node compared to
an ArrayList.

HashSet

Basic Understanding:

What is a HashSet, and how does it differ from a TreeSet?


A HashSet is an implementation of the Set interface that uses a hash table to store elements.

How does a HashSet ensure that it only contains unique elements?


It ensures uniqueness of elements by utilizing the hashCode() method of the objects.

Performance:

What is the average time complexity for adding, removing, and checking for the presence of an element
in a HashSet?
Average time complexities for add, remove, and contains are O(1).

What factors can affect the performance of a HashSet?


Performance can be affected by the quality of the hash function and the load factor.

Iterating:

How can you iterate through the elements of a HashSet? What order do elements appear in?

Use a for-each loop or an Iterator. The order is not guaranteed.

Can you convert a HashSet to an array? How would you do it?


You can convert a HashSet to an array using the toArray() method.

Usage:

When would you use a HashSet instead of a List?


Use a HashSet when you need to maintain a collection of unique elements and order is not important.

Explain a scenario where the HashSet might not be suitable for a specific application.
A HashSet may not be suitable when you need to maintain a sorted order.

Thread Safety:

Is HashSet thread-safe? If not, how can you make it synchronized?

HashSet is not thread-safe. You could use Collections.synchronizedSet(new HashSet<>()) for


synchronization.

HashMap

Basic Understanding:

What is a HashMap, and how does it differ from a Hashtable?

A HashMap is a key-value pair based implementation of the Map interface.

Hashtable (legacy based/ rather old class) is synchronized, meaning it is thread-safe and can be used
safely in a multi-threaded environment without external synchronization.
HashMap (non-legacy based) is not synchronized, so it is preferable in non-threaded applications due
to its performance advantages.

Explain the concept of key-value pairs in a HashMap.

In a HashMap, every entry consists of a key, which acts as an identifier, and a value, which is the data
associated with that key. This structure is fundamental to how data is stored, retrieved, and manipulated
in a HashMap.

Key-Value Pair Structure


Key:A unique identifier used to access a specific value in the HashMap.
Each key must be unique within a given HashMap. If you attempt to put a new entry with a key that
already exists in the HashMap, the existing value will be overwritten with the new value.

Keys can be any object type, but it is standard practice to use immutable objects (like String, Integer,
etc.)
Value:

The data associated with a specific key. Unlike keys, values can be duplicated, meaning multiple keys
can point to the same value. Values can also be any object type, allowing for flexibility in what data can
be stored within the HashMap.

Performance:

What are the average time complexities for get, put, and remove operations in a HashMap?
Average time complexities for get, put, and remove are O(1).

What happens to the elements of a HashMap when its load factor exceeds a certain threshold?
If the load factor exceeds (commonly 0.75), the HashMap resizes and rehashes its entries, which can be
expensive.

Iterating:

How can you iterate through both keys and values in a HashMap?
Iterate through keys using keySet(), values using values(), and both keys and values using entrySet().

Can you discuss the difference between using keySet(), values(), and entrySet() methods?
keySet() - set of keys
values() - set of values
entrySet() is generally the most efficient way to iterate over a HashMap.

Usage:

When would you use a HashMap instead of a TreeMap?


Use HashMap when you need fast access with no concern for order. Use TreeMap when you need
sorted keys.

Discuss potential issues when using mutable objects as keys in a HashMap.

Mutable objects as keys can lead to problems if their state changes while they are in the HashMap.
Programming Questions

Q1 ArrayListExample

package Collections_Framework;

import java.util.ArrayList;

public class ArrayListExample {


public static void main(String[] args) {
// Create an ArrayList to store Integer values
ArrayList<Integer> numbers = new ArrayList<>();

// Adding elements to the ArrayList


numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);

// Printing the ArrayList


System.out.println("ArrayList: " + numbers);

// Accessing an element
int firstElement = numbers.get(0);
System.out.println("First Element: " + firstElement); // Output: 10

// Iterating through the ArrayList


System.out.print("All Elements: ");
for (Integer number : numbers) {
System.out.print(number + " ");
}
System.out.println();

// Removing an element
numbers.remove(2); // Removes the element at index 2 (30)
System.out.println("After Removal: " + numbers);
}
}
o/p
ArrayList: [10, 20, 30, 40]
First Element: 10
All Elements: 10 20 30 40
After Removal: [10, 20, 40]
Q2. LinkedListExample

package Collections_Framework;

import java.util.LinkedList;

public class LinkedListExample {


public static void main(String[] args) {
// Create a LinkedList to store String values
LinkedList<String> fruits = new LinkedList<>();

// Adding elements to the LinkedList


fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Date");

// Printing the LinkedList


System.out.println("LinkedList: " + fruits);

// Accessing elements
String firstFruit = fruits.get(0);
System.out.println("First Fruit: " + firstFruit); // Output: Apple

// Iterating through the LinkedList


System.out.print("All Fruits: ");
for (String fruit : fruits) {
System.out.print(fruit + " ");
}
System.out.println();

// Removing an element
fruits.remove(1); // Removes "Banana"
System.out.println("After Removal: " + fruits);
}
}

o/p

LinkedList: [Apple, Banana, Cherry, Date]


First Fruit: Apple
All Fruits: Apple Banana Cherry Date
After Removal: [Apple, Cherry, Date]
Q3.HashSetExample

package Collections_Framework;

import java.util.HashSet;

public class HashSetExample {


public static void main(String[] args) {
// Create a HashSet to store String values
HashSet<String> colors = new HashSet<>();

// Adding elements to the HashSet


colors.add("Red");
colors.add("Green");
colors.add("Blue");
colors.add("Yellow");
colors.add("Red"); // Duplicate, will not be added

// Printing the HashSet


System.out.println("HashSet: " + colors); // The order may vary

// Checking for an element


boolean hasBlue = colors.contains("Blue");
System.out.println("Contains Blue? " + hasBlue); // Output: true

// Iterating through the HashSet


System.out.print("All Colors: ");
for (String color : colors) {
System.out.print(color + " ");
}
System.out.println();

// Removing an element
colors.remove("Green");
System.out.println("After Removal: " + colors);
}
}

o/p

HashSet: [Red, Blue, Yellow, Green]


Contains Blue? true
All Colors: Red Blue Yellow Green
After Removal: [Red, Blue, Yellow]
Q4. HashMapExample

import java.util.HashMap;

public class HashMapExample {


public static void main(String[] args) {
// Creating a HashMap to store key-value pairs
HashMap<String, Integer> map = new HashMap<>();

// Adding key-value pairs


map.put("Alice", 30); // Key: "Alice", Value: 30
map.put("Bob", 25); // Key: "Bob", Value: 25
map.put("Charlie", 35); // Key: "Charlie", Value: 35

// Retrieving a value using a key


int ageOfBob = map.get("Bob");
System.out.println("Bob's age: " + ageOfBob); // Output: Bob's age: 25

// Modifying a value
map.put("Alice", 31); // Updating Alice's age

// Removing a key-value pair


map.remove("Charlie");

// Displaying the contents of the HashMap


System.out.println(map); // Output: {Alice=31, Bob=25}
}
}
o/p

Bob's age: 25
{Bob=25, Alice=31}

You might also like