w0rpzone

Blog

A Quick, but Important Improvement for Your Java Code

Dear all Java Developers, please stop doing this.

public void List<MyObject> getValues() {
    return new ArrayList(privateList);
}

Please start doing this instead.

public void Collection<MyObject> getValues() {
    return Collections.unmodifiableCollection(privateList);
}

Here are the reasons why.

  1. Both List and Set are sub-interfaces of Collection, so both work. Forward ranges are better than random access ranges in most cases.
  2. You will cut your memory usage by more than half for any object which has a method like this.
  3. The resulting collection is immutable (though not transitively), so the return value cannot modify the collection you passed.
  4. You'll get an added guarantee that when passed down through several functions, the collection will be the same as when it was at the top.

Post Your Comment

Need help with comment formatting?

Okay, here's a cheat sheet for you. Click here to get rid of this.

Choose a help topic below. Raw HTML for basic formatting allowed, and other HTML will be escaped. Other Markdown syntax is valid, but probably not relevant.

*italic* **bold**
_italic_ __bold__
1. Item #1
2. Item #2

* Unordered list item
* Unordered list item
Three backticks are your friend here: ```square = lambda x: x * x```

Also in a block like so:

```python
def square(x):
  return x * x
```