0% found this document useful (0 votes)
8 views2 pages

Java Generics and Collections Exercise

This document outlines Exercise 08 for the UIT3361 course on Object-Oriented Programming Using Java, focusing on Generics and Collections. Students are required to complete various programming tasks, including implementing a generic Bubble Sort, creating a To-Do List application, managing employee records with a HashMap, and developing a LibraryApp using TreeSets and HashMaps. The homework is due by 10 PM on September 15, 2025, with a grace period until midnight.

Uploaded by

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

Java Generics and Collections Exercise

This document outlines Exercise 08 for the UIT3361 course on Object-Oriented Programming Using Java, focusing on Generics and Collections. Students are required to complete various programming tasks, including implementing a generic Bubble Sort, creating a To-Do List application, managing employee records with a HashMap, and developing a LibraryApp using TreeSets and HashMaps. The homework is due by 10 PM on September 15, 2025, with a grace period until midnight.

Uploaded by

Sh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SSN College of Engineering

Department of Information Technology

UIT3361 – Object-Oriented Programming Using Java


2025– 2026

Exercise — 08

Generics and Collections in Java

• This homework is due by 10 PM on September 15, 2025


• Grace period may be given up to midnight of September 15, 2025
• You can upload only one ZIP file
• The naming convention is “<Your first name (first letter capital and all the other letters
small)>- [Link]”

Part A

Write a Java program for the following problem statements


1. Write a Java program to implement a generic Bubble Sort algorithm. The program should
define a generic method bubbleSort(T[] array) that can sort an array of any type T,
provided T implements the Comparable<T> interface. Use this method to sort an array of
integers representing student roll numbers, an array of strings representing student names,
and an array of doubles representing student grades. Finally, display the arrays before and
after sorting to verify the correctness of the program.
2. A shop uses a generic class Product<T> to store product IDs. The ID can be either
numeric (e.g., 101) or alphanumeric (e.g., "P001"). Apart from storing the ID, add a
functionality boolean compareId(T otherId) that checks if the stored ID matches another
ID given by the user. Demonstrate this feature with both Integer and String product IDs.
3. You are required to develop a simple To-Do List Application in Java named ToDoApp.
The application should allow users to manage their daily tasks efficiently using the
ArrayList collection. Implement and demonstrate the following sequence of operations:
a. Add Tasks: Insert at least five tasks (for example: “Buy groceries”, “Finish
homework”, etc.) into the to-do list.
b. Display Tasks: Print all tasks along with their corresponding indices.
c. Update Task: Modify one task in the list (for instance, change “Finish homework”
to “Submit homework”).
d. Search Task: Search for a specific task in the list and display whether it exists.
e. Remove Task: Delete one task and print the updated task list.
f. Count Tasks: Display the total number of tasks currently present in the list.
g. Clear Tasks: Remove all tasks from the list and confirm that the list is empty.
4. Write a Java program called StudentRanking that uses a TreeSet to store and display
student scores in ascending order. Create a TreeSet<Integer> to hold student scores.
a. Insert at least five scores (e.g., 85, 92, 70, 60, 90).
b. Display all scores – confirm that they are automatically sorted.
c. Print the lowest score and the highest score.
d. Remove one score and display the updated ranking.
5. Write a Java program called EmployeeDirectory that uses a HashMap to manage
employee records. Create a HashMap<Integer, String> where the key is the employee ID
and the value is the employee name.
a.
Insert at least five employees into the directory. Example: 101 "Alice", 102 "Bob", etc.

b. Display all employee entries (ID Name).


c. Search for an employee by ID and print their name if found.
d. Update one employee’s name (e.g., change "Bob" to "Robert").
e. Remove one employee record using their ID and show the updated directory.
f. Print the total number of employees in the directory.

Part B

6. Write a Java program called LibraryApp that manages a collection of books by their
topics. Use a TreeSet to store and display unique book categories (e.g., Fiction, Science,
History). For each category, use a HashMap where:
● The key is the broad topic under that category (e.g., Data Structures, Java, DBMS
etc). The value is an ArrayList of specific book titles belonging to that topic.
● Insert at least 2 categories, each with at least 2 topics and multiple books under
each topic.
● Display all categories in sorted order using the TreeSet.
● For each category, display the topics and the list of books under them.

******

Common questions

Powered by AI

Key considerations when implementing a program to manage employee directories using HashMap in Java include ensuring that keys are unique and choosing a proper hash function to minimize collisions, which can degrade performance. It is important to consider the load factor and initial capacity of the HashMap to balance memory usage and performance. Managing nullable keys and values efficiently and ensuring consistent hashCode and equals implementations are crucial for maintaining the integrity of entries. These considerations directly impact the program's performance by affecting the time complexity of operations, collision resolution effectiveness, and overall memory efficiency .

In managing employee records using a HashMap<Integer, String> in a Java program, you can perform several operations: search for an employee by ID to print their name if found, update an employee’s name (such as changing 'Bob' to 'Robert'), and remove an employee record using their ID, showing the updated directory. You can also print the total number of employees in the directory. The advantage of using a HashMap lies in its efficiency for these operations; it provides average constant time complexity O(1) for insertion, search, and removal operations, making it ideal for handling large volumes of data where quick access to records by ID is necessary .

To define a generic Bubble Sort algorithm in Java that can handle different data types like integers, strings, and doubles, you need to implement a generic method called bubbleSort(T[] array). This method should accept an array of any type T, provided T implements the Comparable<T> interface. This ensures that the elements can be compared with each other during sorting. The Comparable interface provides a method compareTo that is used to determine the order of elements, allowing the bubble sort algorithm to swap elements as needed to sort the array. For demonstration, you can sort arrays of integers (student roll numbers), strings (student names), and doubles (student grades) and display them before and after the sorting to validate the method's correctness .

In a generic class Product<T> in Java designed to manage product IDs, you can store IDs that may be either numeric or alphanumeric. One key functionality to add is a method called compareId(T otherId) that checks if the stored ID matches another ID provided by the user. This can be demonstrated using both Integer and String product IDs. For example, you could instantiate Product<Integer> to store numeric IDs like 101, and Product<String> for alphanumeric IDs like 'P001'. You then test the compareId method to verify if it correctly identifies when two IDs are the same .

To structure a LibraryApp in Java using TreeSet and HashMap effectively, you can manage book collections by topics as follows: Use a TreeSet to store and maintain unique book categories (e.g., Fiction, Science, History) in a sorted manner. For each category, employ a HashMap where the key is a broad topic under that category (e.g., Data Structures), and the value is an ArrayList of specific book titles under that topic. You should insert at least two categories, each with at least two topics and multiple books. This structure allows you to efficiently display all categories in sorted order using TreeSet and provide detailed views of topics and corresponding book lists under each category using HashMap, enhancing organization and retrieval efficiency .

Potential challenges in implementing task management using ArrayList in a Java To-Do List Application include handling concurrent modifications, ensuring thread-safety, and managing memory usage efficiently. Concurrent modifications can lead to errors if multiple threads access or modify the ArrayList simultaneously. To address this, you could use synchronized lists or other concurrent collections. Ensuring thread-safety might require Java's synchronized keyword or locks. Proper memory management can be handled by regularly trimming the ArrayList using the trimToSize() method after removing tasks, minimizing its footprint. Carefully managing these challenges can lead to a robust application capable of dynamic tasks efficiently .

The use of TreeSet in the Java program StudentRanking ensures that student scores are automatically sorted in ascending order because TreeSet is a part of the Java Collections Framework that implements the SortedSet interface. This collection maintains elements in their natural order or according to a specified comparator. Consequently, when you insert scores such as 85, 92, 70, 60, and 90, they are automatically sorted, and operations like getting the minimum and maximum scores become straightforward and efficient. This automated sorting aids performance assessment by simplifying rank determination and comparisons without needing additional sorting logic .

Using TreeSet and HashMap for categorizing books in a library application offers several benefits: TreeSet automates sorting and ensures unique categories, allowing efficient access and display of sorted categories. HashMap allows for quick lookups and dynamic management of topics and book lists under each category. However, limitations include the inability to store duplicate book categories with TreeSet and potentially higher memory usage due to HashMap's storage structure for managing multiple array lists. These structures require careful handling, such as iterating over categories cautiously to avoid unexpected behavior or performance issues during large-scale operations .

The compareId method in a generic Java class enhances functionality by allowing for a flexible and reusable code structure that can accommodate different types of IDs, such as Integer and String, without needing separate implementations for each type. Unlike using primitive types directly, the generic approach avoids coding redundancy and makes the codebase more adaptable to changes, such as accommodating new types of IDs in the future without significant restructuring. This method within a generic class allows you to easily compare and validate IDs, improving the maintainability and scalability of the application .

To develop a To-Do List Application in Java using ArrayList collections, you should follow these steps: First, implement a method to add tasks, where you insert at least five tasks into the to-do list. Next, provide a functionality to display all tasks along with their indices. You should also include an update capability to modify tasks, such as changing 'Finish homework' to 'Submit homework'. Implement a search feature to check for the presence of a specific task in the list, and a remove function to delete tasks and print the updated list. Finally, provide a count of the total number of tasks and a clear method to remove all tasks, confirming the list is empty. These steps help users efficiently manage their tasks by structuring their to-do list operations clearly and allowing for easy manipulation of the tasks .

You might also like