Java Collection: Optionale Operation in Schnittstelle

Zyboarg

Ensign
Registriert
Juli 2012
Beiträge
218
Hey Leute,
als ich mir heute mal die API zu den Java Collections durchgelesen habe ist mir aufgefallen, dass einige Methoden als optional deklariert sind.
Da die Collection API allerdings vor Java 1.8 und den default Methoden in Schnittstellen geschrieben wurde frage ich mich wieso der Code dafür überhaupt compiliert wird, bzw. wieso man das nicht irgendwie anders gelöst hätte...

Code:
public boolean  add(E e) {

        throw new UnsupportedOperationException();
    }

so in der Art muss das ja irgendwie in der Collection stehen oder nicht?

Lg Zyboarg
 
Geh mal in deine Java Installation und schau mal nach src.zip , wenn du den source code installiert hast.
Da siehst dann das List Interface und dessen Implementierungen LinkedList und ArrayList
 
Zuletzt bearbeitet:
Da steht auch nicht viel drinnen... Scheint wohl eine besonderheit zu sein.
So steht es in List drinnen:

Code:
boolean add(E e);

mit dem Kommentar:

Appends the specified element to the end of this list (optional operation).

Lists that support this operation may place limitations on what elements may be added to this list. In particular, some lists will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. List classes should clearly specify in their documentation any restrictions on what elements may be added.

Parameters:
e element to be appended to this list
Returns:
true (as specified by Collection.add(java.lang.Object))
Throws:
java.lang.UnsupportedOperationException if the add operation is not supported by this list
java.lang.ClassCastException if the class of the specified element prevents it from being added to this list
java.lang.NullPointerException if the specified element is null and this list does not permit null elements
java.lang.IllegalArgumentException if some property of this element prevents it from being added to this list
 
optional steht da bei allem dran. werden wohl alle Methoden sein die man nutzen kann aber nicht muss.
 
Schau dir zum Beispiel an, wie Collections.emptyList() implementiert ist. Da hat man sich diese Optionalität zu Nutze gemacht. Hätte man wahrscheinlich auch andersherum machen können, aber entsprach vielleicht dem damaligen Zeitgeschmack.
 
Zurück
Oben