Collections and Equality


The student information system will need to create a course catalog that contains all of the Course objects. You will thus need to be able to store a Course in a collection, then verify that the collection contains the object.

 package sis.studentinfo; import junit.framework.*; import java.util.*; public void testEquality() {    Course courseA = new Course("NURS", "201");    Course courseAPrime = new Course("NURS", "201");    assertEquals(courseA, courseAPrime);    ...    // containment    List<Course> list = new ArrayList<Course>();    list.add(courseA);    assertTrue(list.contains(courseAPrime)); } 

The contains method defined in ArrayList loops through all contained objects, comparing each to the parameter using the equals method. This test should pass with no further changes. In fact, the test for containment is more of a language test. It tests the functionality of ArrayList, by demonstrating that ArrayList uses the equals method for testing containment. The containment test does not add to the equality contract. Feel free to remove it.

What about using the Course as a key in a HashMap object?

 public void testEquality() {    Course courseA = new Course("NURS", "201");    Course courseAPrime = new Course("NURS", "201");    // ...    Map<Course, String> map = new HashMap<Course, String>();    map.put(courseA, "");    assertTrue(map.containsKey(courseAPrime)); } 

The above bit of test demonstrates a Map method, containsKey. This method returns true if a matching key exists in the map. Even though a Map is a collection, just as a List is, this test fails! To understand why, you must understand how the HashMap class is implemented.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net