0% found this document useful (0 votes)
14 views

Lab 11

The document outlines a lab assignment for CSC245B focusing on Java data structures, including Bounded Generics, Comparable Interface, ArrayList, and LinkedList. It consists of three main problems: implementing a SortedArrayList with custom add and search methods, using Java's built-in LinkedList to perform various operations, and creating a custom singly linked list with specific functionalities. The assignment emphasizes understanding of generics, sorting, searching algorithms, and linked list operations.

Uploaded by

Lea
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)
14 views

Lab 11

The document outlines a lab assignment for CSC245B focusing on Java data structures, including Bounded Generics, Comparable Interface, ArrayList, and LinkedList. It consists of three main problems: implementing a SortedArrayList with custom add and search methods, using Java's built-in LinkedList to perform various operations, and creating a custom singly linked list with specific functionalities. The assignment emphasizes understanding of generics, sorting, searching algorithms, and linked list operations.

Uploaded by

Lea
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/ 5

COVERED TOPICS

 Bounded Generics
 The Comparable Interface
 ArrayList
 Searching and Complexity
 Built-in LinkedList
 Custom Linkedlist
 Iterator and Iterable interfaces

Image source: https://www.jrebel.com/blog/top-java-development-tools-


and-software Guest ACC
CSC245B – Objects and Data Abstraction Lab

CSC245B LAB 11
Spring 2025

Page 0 of 4
Problem 1 – Sorted ArrayList

Before solving this problem, make that you are familiar with Java’s Comparable interface (check
ComparableDemo.java that is given with the lab files for a review).

The code below defines a generic SortedArrayList class. As you can see, the class has a type parameter T. The
specification <T extends Comparable<T>> means that the type T is constrained to implement Comparable<T>,
meaning that the user can only use types that implement the Comparable interface, and more specifically, the user
can only specify types that can be compared with their own type.

Examples of valid types that can be used as a value for T:

- Integer because Integer implements Comparable<Integer> (Integer can be compared with another Integer)
- String because String implements Comparable<String>
- Person (as defined in ComparableDemo.java) because Person implements Comparable<Person>

The reason for this constraint is that the SortedArrayList, by design, keeps its elements (of type T) consistently
sorted, and to be able to sort, the elements need to be Comparables (there should be a definition of how they are
compared). Your task is to:

a) Read and understand the provided skeleton code


b) Implement the add method, so that it adds a new element to the ArrayList attribute L while making sure
that the list remains sorted in non-decreasing order. Note: You are not allowed to use built-in sorting
methods, and you are required to provide a solution of O(n) complexity, where n is the size of the list when
add is called.
c) Implement the search method which takes a target to search for in the sorted array L. The method returns
the index where the target is found or returns -1 if not found. Since L is sorted, you are required to use the
binary search algorithm (don’t use built in search methods). You are also required to provide a recursive
solution. Finally, you should not change the method signature, but you can use a private helper method if
needed.

Expected output of the driver program in main:

Printing sorted array using get() and size(): 1 4 13 15 22


Printing sorted array using toString(): [1, 4, 13, 15, 22]
Printing sorted array after removing 13: [1, 4, 15, 22]

Testing search method: 0 1 2 3 -1


import java.util.ArrayList;

public class SortedArrayList<T extends Comparable<T>> {


private ArrayList<T> L;

public SortedArrayList() {
this.L = new ArrayList<T>();
}

public void add(T element) {


//TODO your implementation goes here
}

public void remove(T element) {


L.remove(element);
}

public int size() {


return L.size();
}

public T get(int index) {


return L.get(index);
}

@Override
public String toString() {
return L.toString();
}

public int search(T target) {


//TODO your implementation goes here
//you can use a private helper method
}

public static void main(String[] args) {


SortedArrayList<Integer> sortedArray = new SortedArrayList<>();
sortedArray.add(13);
sortedArray.add(1);
sortedArray.add(15);
sortedArray.add(22);
sortedArray.add(4);
System.out.print("Printing sorted array using get() and size(): ");

for(int i=0; i<sortedArray.size();i++) {


System.out.print(sortedArray.get(i) + " ");
}

System.out.println("\nPrinting sorted array using toString(): " + sortedArray);

Integer x = 13;
sortedArray.remove(x);
System.out.println("Printing sorted array after removing 13: " + sortedArray);

System.out.print("\nTesting search method: ");

for(int i=0; i<sortedArray.size();i++) {


System.out.print(sortedArray.search(sortedArray.get(i))+" ");//should return i
}
System.out.println(sortedArray.search(100));
}
}
Problem 2 – Built-in LinkedList and its Iterator

In this problem, you will practice using Java’s builtin LinkedList and different ways to iterate over it. In all the parts
below, the LinkedList objects are assumed to be lists of integers. Write a Java program that includes:

a) A minValue method that takes a LinkedList as argument and returns the minimum value in the LinkedList.
In this method, you are asked to iterate using a regular for loop that loops over all the indices in the
LinkedList and uses these indices to get the elements in the list (i.e., use the get and size methods).
b) A swapElements method that takes three arguments: a LinkedList, index1, and index2 where index1 and
index2 are integers. The method first checks if the passed indices are valid (i.e., within the range of the list);
if not, it throws an IllegalArgumentException (you can pass an error message: At least one index is
outside the bounds!). Otherwise, if the indices are valid, the method swaps the element at index1 with
the element at index2 in the LinkedList. This method does not return a value. To get full credits, you are
asked to use ListIterator to swap; i.e., use the listIterator() method of list which returns an object of type
ListIterator. Hint: check the documentation of ListIterator and also the two overloaded listIterator methods
in the List class (the tables in the slides).
c) A sumOfEvens method that also takes a LinkedList as an argument and returns the sum of all the even
integers in the LinkedList. In this method, you are asked to iterate over the LinkedList using the enhanced
for-loop (also known as the for-each syntax).
d) A uniqueElements method, that takes a LinkedList as an argument and returns a new LinkedList including
the same elements of the input list after removing the duplicates. To get full credits, all iterations in this
method should be done using ListIterator, and the contains method of the LinkedList class should not be
used. Also make sure not to mutate the list that is passed as argument.
e) A main method that reads integers from the user into a LinkedList until a -1 is given to end, and then calls
and displays the outputs of all the methods created earlier. Two sample runs are shown below.

Sample Input/Output 1:

Please enter integers and -1 to end:


4
5
2
1
1
-1
Contents of the LinkedList: [4, 5, 2, 1, 1]
Minimum value in the LinkedList is: 1
Enter index1 and index2: 4 5
Swapping Elements at 4 & 5...
Exception in thread "main" java.lang.IllegalArgumentException: At least one index
is outside the bounds!
at lab11.Problem1.swapElements(Problem1.java:55)
at lab11.Problem1.main(Problem1.java:32)
Sample Input/Output 2:

Please enter integers and -1 to end:


4 11 12 6 1 1 1 2 8 98 65 4 5 4 -1
Contents of the LinkedList: [4, 11, 12, 6, 1, 1, 1, 2, 8, 98, 65, 4, 5, 4]
Minimum value in the LinkedList is: 1
Enter index1 and index2: 0 7
Swapping Elements at 0 & 7...
List now (after swapping): [2, 11, 12, 6, 1, 1, 1, 4, 8, 98, 65, 4, 5, 4]
Sum of even numbers is: 138
LinkedList without duplicates: [2, 11, 12, 6, 1, 4, 8, 98, 65, 5]
Problem 3 – Custom (User-defined) Singly LinkedList

Open the “Problem3.java” file that is given with the assignment document. The file includes a generic Node class, a
MyLinkedList class representing a list of nodes starting from a node called head, and a Problem2 class including a
test program for the MyLinkedList class. You are asked to read and understand the code and the different given
methods (it is recommended that you write it again yourself), and you are also asked to add the following methods
to the MyLinkedList class (indicated by //TODO comments in the code):

a) void add (E data): this method adds a node holding the given data at the end of the list.
b) boolean remove(E data): this method removes from the list the first occurrence of a node with the given
data and returns true assuming that such a node is found. The method returns false if there is no node in the
list with the given data.
c) void reverse( ): this method reverses recursively the nodes in the list (you need to reverse the link directions
not swap values; for example if n1 and n2 are nodes in the linkedlist where n1.next = n2, then after reversing
n2.next = n1 (n2n1 instead of n1n2). To achieve this, you are first asked to define and implement a
private helper method with the following signature:

private Node<E> reverseRecursive(Node<E> current, Node<E> previous)

By definition: this helper method reverses the links of the linkedlist starting
at the current node, and it returns the head of the reversed list.

The reverse( ) method can then be implemented as a wrapper for the method above as follows:

public void reverse() {

head = reverseRecursive(head, null);

A driver program is given in main and the expected output is shown on the next page.

Expected output of the given test program:

list1: [1, 2, 3, 4]
list1 reversed: [4, 3, 2, 1]

5 is in list1? false
list1 after list1.remove(5): [4, 3, 2, 1]

3 is in list1? true
list1 after list1.remove(3): [4, 2, 1]

list1 after removing all elements: []

list2 reversed:
[If I must die, you must live. To tell my story, to sell my things.
, To buy a piece of cloth and some strings,
, make it white with a long tale so that a child somewhere in Gaza while looking
heaven in the eye,
, awaiting his dad who left in a blaze and bid no one farewell,
, not even to his flesh, not even to himself,
, sees the kite, my kite you made, flying up above
, and thinks for a moment an angel is there bringing back love.
, If I must die, let it bring hope, let it be a tale.
]

You might also like