Difference between revisions of "Iterable Immutable List Assignment"
Line 31: | Line 31: | ||
public static <E> ImmutableList<E> brackets(E... elements)</nowiki> | public static <E> ImmutableList<E> brackets(E... elements)</nowiki> | ||
− | <code>brackets</code> accepts [https://docs.oracle.com/javase/8/docs/technotes/guides/language/varargs.html variable length arguments] as specified by the <code>...</code> syntax. | + | <code>brackets</code> accepts [https://docs.oracle.com/javase/8/docs/technotes/guides/language/varargs.html variable length arguments] as specified by the <code>...</code> syntax. When implementing the <code>brackets</code> method you can treat <code>elements</code> as an array. Combining generics and varargs can be problematic if the implementation lets the E[] escape since it will actually be an Object[]. The [[https://docs.oracle.com/javase/7/docs/api/java/lang/SafeVarargs.html @SafeVarargs]] annotation indicates a promise that you will rely [https://stackoverflow.com/questions/14231037/java-safevarargs-annotation-does-a-standard-or-best-practice-exist only on the elements of the array being of type E]. This should not be a problem. |
=Test= | =Test= | ||
{{TestSuite|ListsTestSuite|immutable.list.assignment}} | {{TestSuite|ListsTestSuite|immutable.list.assignment}} |
Revision as of 19:14, 30 July 2019
Contents
Code To Implement
DefaultImmutableList
class: | DefaultImmutableList.java | ![]() |
methods: | head tail isEmpty iterator |
|
package: | immutable.list.assignment | |
source folder: | src/main/java |
default constructor
head and tail constructor
head
tail
isEmpty
iterator
Lists
Lists
is a class which holds a number of static methods. As we know, in the Kingdom of Nouns, Verbs must always have an escort.
The first two static methods nil
and cons
will each call a constructor of the DefaultImmutableList
class. The third method brackets
will use nil
and cons
to build up the desired ImmutableList.
class: | Lists.java | ![]() |
methods: | nil cons brackets |
|
package: | immutable.list.assignment | |
source folder: | src/main/java |
nil
public static <E> ImmutableList<E> nil()
Analogous to the SML List nil constructor.
Note: often SML programs use empty brackets []
instead of nil
.
cons
public static <E> ImmutableList<E> cons(E head, ImmutableList<E> tail)
Analogous to the SML List :: constructor.
brackets
@SafeVarargs public static <E> ImmutableList<E> brackets(E... elements)
brackets
accepts variable length arguments as specified by the ...
syntax. When implementing the brackets
method you can treat elements
as an array. Combining generics and varargs can be problematic if the implementation lets the E[] escape since it will actually be an Object[]. The [@SafeVarargs] annotation indicates a promise that you will rely only on the elements of the array being of type E. This should not be a problem.
Test
class: | ListsTestSuite.java | ![]() |
package: | immutable.list.assignment | |
source folder: | src/test/java |