This is the first part of HW11.
Download these three files:
ListTest
. This class may not contain any non-static methods or data members.List
interface. Make sure that you test failure cases as well as nicely-behaved, ordinary cases. Try hard to trick the implementation into making mistakes. Use the “Mystery” List implementation as your implementation type for these tests (but keep in mind that you will swap this out for your own implementation type later on, so design your code so that this replacement is easy).
If any test fails, print out an easily-distinguished error message; something like
*** TEST FAILED: Expected ABC; Got null ***
It is your choice what to print when tests succeed; options include printing nothing, printing a short description of what you're testing, printing the (correct) result that the test produced, or something else.
Note that it is extremely unlikely that a correctly-written test will fail when using the provided List implementation. If you do find a way to trick it into producing incorrect results, please let me know so I can fix it!
When you write your List implementation, you will have to implement the toArray()
method. The purpose of toArray()
is to make it easy for a caller to iterate through all the items in your list.
However, note that toArray()
returns an Object[]
— that is, an array of objects of type Object
. Why Object
instead of the generic type? The answer is actually shockingly complicated, and it all comes down to decisions that the Java designers made when they introduced generic types into the language. The long and the short of it, though, is that Java doesn't have any good way to preserve the type information in the output of toArray()
.
You can still use it in your tests, though, and you should. For example, here is a for-each loop that compiles and runs error-free (provided that L
was declared as List<String> L
):
for(Object o : L.toArray()) { String s = (String) o; System.out.println(s); }
Implementing the iterator()
method is an entirely optional component of Part 3 of this assignment; that part includes a separate tutorial on implementing it if you choose to try. iterator()
works correctly in the mystery List implementation that I provided. However, if you don't plan on implementing iterator()
in your own List implementation, then don't worry about writing tests for it. If you do plan to implement this method, a for-each loop is a good way to test this functionality, too. For example, the following code implicitly makes use of the iterator()
method, as well as the hasNext()
and next()
methods of the resulting iterator:
for(String s : L) { System.out.println(s); }