Aug 24

Assigning a collection to another collection is okay in most cases. But today I encountered a case where the assignment doesn’t quite work. See the following block of code.

class Foo {
  private Collection aCollection =
    new TreeSet(new SomeKindOfComparator());

  public void setACollection(List aCollection) {
    this.aCollection = aCollection;
  }
}

The intent is to keep the collection sorted and avoid duplication. But as soon as the assignment in the setter happens, the instance variable aCollection’s reference is changed to be the List. There won’t be any error or exception at either compiling time or runtime. You will be wondering why that collection is not sorted and contains duplicate entries.

Leave a Reply

preload preload preload