CPT102 – Data Structures Lab 1
Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit
CPT102 – Data Structures
Lab 1 – Generic type, bag ADT
Aim
Understand java generic type and bag ADT.
Resources
All Java files you need are found on Learning Mall.
Tips
Check lecture notes for lecture 4 to understand Bag collection before starting.
Bag Implementation – convert IntArrayBag to ArrayBag
At this Lab session, we are going to covert the IntArrayBag class to an ArrayBag class.
Download IntArrayBag.java file from Learning Mall. An IntArrayBag is a collection of int numbers. The same number may appear multiple times in a bag.
Download ArrayBag.java file from Learning Mall. An ArrayBag is a generic collection of references to objects (objects has the same type). The same object may appear multiple times in a bag.
Have a look of the declaration of this class.
Task 1: We talked about the two constructors in IntArrayBag class. In ArrayBag class, we will create two constructors as well. Please use the same idea in IntArrayBag class, to finish the implementation of the second constructor in ArrayBag.
Task 2: Implement a grab() method in ArrayBag class, which takes no parameter, returns a random element from the bag.
Note: make sure you check the condition that the bag is not empty.
Task 3: Have a read of remove() method in IntArrayBag. Implement the same method in ArrayBag.
Note: the element can be null. Check the countOccurrences() method, use the same idea to deal with null in remove() method.
Test:
Download ArrayBagTest.java file to test your grab() method. The output should be similar like this:
Use addMany() method to add more elements in your bags, test your remove() method.
Note: If you cannot finish all the tasks, please do them as homework.
2023-04-18
Generic type, bag ADT