Java & Functional Programming Paradigm - How do I make my arrays immutable

Thezi :

I'm trying to make code that follows the functional programming paradigm, which follows immutability very religiously, but the only way I know how to make my array even close to being immutable is by using

List<Integer> items = Collections.unmodifiableList(Arrays.asList(0,1,2,3));

I am unsure whether this makes the array immutable or just unmodifiable. If the command above does not make the array immutable what would?

Alexey Romanov :
  1. You can't mutate the underlying array (or the list returned by Arrays.asList) except by reflection. However, arrays aren't really relevant here; don't confuse arrays and lists!

  2. Since Java 9, List.of(0, 1, 2, 3) achieves the same.

  3. To do operations which produce new collections, you'll have to go through streams. You may also want to consider third-party libraries, e.g. Guava (this link is to their immutable collections page). Or even better PCollections, which provides only immutable collections and more functional implementations of them than Guava does.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306016&siteId=1