For example, in Jsoup, they defined a class Elements to collect Element(s).
It's common to define a class A and As which contains a lot of A(s). But why? Why don't we just use ArrayList or something?
The Elements
class in JSoup has many specific methods to its function e.g.
toggleClass(String className)
html()
Which wouldn't be available on ArrayList. I guess ArrayList
could have been extended, but the author of Elements
has gone for composition. Elements
HAS-A ArrayList
instance which it keeps private. Elements
exposes methods of the List interface, bespoke methods and others.
But Elements
is backed by an ArrayList - this way the author can also decorate the methods of ArrayList he chooses to make public via his own Class. This is an extract from the source code:
private List<Element> contents;
public Elements() {
contents = new ArrayList<Element>();
}
BTW: You used to see wrappers pre Java 5 to give type safety to Java Collections
, but since Java 5 Generics have stopped a lot of this.
For this special example looking at the API shows you that in addition to the plain collection methods, Elements
provides related to HTML processing. Hence the implementation of a custom collection. Beside you'll notice that Elements
implements Iterable
, Collection
and List
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With