ArraySet

Chapter: ArraySet

You have the file ArraySet.java from the textbook source. There are some changes you will need to make.


Exercise 4

Fix ArraySet.java by:
  1. Make BlueJ-style javadoc comments at the top of the file
  2. Comment out or delete the package statement
  3. Comment out or delete the import jss2.exceptions line (That is because you just created both those classes in your current folder).
  4. Add methods corresponding to the methods you added to the interface above. For now, the bodies can be as simple as
    {
      return null;
    }
    { 
      return false;
    }
    {
      return null;
    }
    


At this point, your code should fail to compile with an error message about needing a try for the two statements

temp1.remove(obj);
temp2.remove(obj);
To get rid of the error, you need to replace those two lines with:
try {
  temp1.remove(obj);
  temp2.remove(obj);
}
catch (Exception e) { 
  return false;
}

Finally you code will compile. There will be three warnings and they pertain to problems concerning types. One line generating a warning reads:

    contents = (T[])(new Object[DEFAULT_CAPACITY]);
Java is a little unhappy about the cast (T[]). So am I. What we want to do is to create an array of T. The code to do that would be
    contents = new T[DEFAULT_CAPACITY];

But if you put that code in place of the ugly typecast code you will get an error. Java will accuse you of generic array creation. This is something that the Java designers have not yet figured out. The only workaround I (and apparently the authors of the textbook code) know to this problem is to first of all make an array of Object via new Object[DEFAULT_CAPACITY] and then cast that Object array into a T array via (T[]). That generates a warning because the (compile-time) type checker cannot check to make sure that the array can actually be considered to be an array of T. But it's only a warning. Dynamic array creation is an error and the compiler will fail. Unchecked casts, while ugly and inelegant, only generate warnings.

So now you have the textbook code, slightly enhanced, and compiled. You also have three incorrect methods: intersection, subset and diff. We will proceed to test this code, and then have you correctly implement the three extra methods.


rhyspj@gwu.edu