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.
- Both List and Set are sub-interfaces of Collection, so both work. Forward ranges are better than random access ranges in most cases.
- You will cut your memory usage by more than half for any object which has a method like this.
- The resulting collection is immutable (though not transitively), so the return value cannot modify the collection you passed.
- 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.