To work with the ArrayList implementation we developed in class.
In this class you are free to use whichever Java programming environment you are most comfortable with. If you have something that works for you, then you should probably keep on using it.
In the examples I use throughout this class, I will use the Vim text editor, and the command-line Java compiler. You can use this if you wish, but I don't require you to.
If you need help installing Java or an IDE, please let me know and I will be happy to assist you!
For this lab you will be adding a couple of methods to the DynamicList class we developed.
void set(int index, Type item)
- this method should change an item in the list
to the value passed in. It should also throw IndexOutOfBoundsException if the index is not valid.int lastIndexOf(Type item)
- this method should search the array, but starting at the end
of the array and working towards the front. If it's not found it should return -1.void trimToSize()
- this method should resize the array to be exactly large enough to hold
the items stored in it. For instance if the capacity is 10, but there are only 6 items, calling trimToSize
should resize it to size 6. For testing, you should print the size and capacity after doing the resize.You can test your code with the following main class:
public class DynamicListTest {
public static void main(String args[]) {
DynamicList<String> names = new DynamicList<String>(30);
names.add("Alice");
names.add("Bob");
names.add("Claire");
names.add("Dominic");
names.add("Estelle");
names.add("Frank");
names.add("Gwen");
names.add("Hugo");
names.add("Irene");
names.add("Claire");
names.add("Jack");
// test the set method
names.set(1, "Billy");
System.out.println(names.get(1));
try {
names.set(100, "Slartibartfast");
} catch (IndexOutOfBoundsException e) {
System.out.println("Exception thrown correctly");
}
// test the last index method
int index = names.lastIndexOf("Claire");
System.out.println("Last index of Claire is " + index);
// call the trimToSize method -- should ensure that works in method
names.trimToSize();
// print the final list
System.out.println("List contents:");
for (int i = 0; i < names.size(); i++) {
System.out.println("\t" + names.get(i));
}
}
}
This code should then produce the following output:
Billy Exception thrown correctly Last index of Claire is 9 Size = 11 Capacity = 11 List contents: Alice Billy Claire Dominic Estelle Frank Gwen Hugo Irene Claire Jack
When you are finished, please upload your code to the Canvas page for this assignment. Please send the .java file(s) only.
Copyright © 2024 Ian Finlayson | Licensed under a Creative Commons BY-NC-SA 4.0 License.