Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does some libs define their own collections?

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?

like image 541
Lai Yu-Hsuan Avatar asked May 10 '11 15:05

Lai Yu-Hsuan


2 Answers

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.

like image 77
planetjones Avatar answered Sep 28 '22 16:09

planetjones


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.

like image 21
gabuzo Avatar answered Sep 28 '22 14:09

gabuzo