What Is the Alternative of List. Of() in Java If I'm Using Java 8 Using Sts

I'm trying to create one Spring Boot Application through STS4 but while I'm using List.of() it never give any suggestion like this due to which getting {beans.factory.UnsatisfiedDependencyException} kind of exception

4

1 Answer

Just bear in mind the following difference:

  • List.of was introduced with Java 9, and it returns an unmodifiable List. The list returned by the method cannot be resized nor modified, which means, you cannot add, remove or replace any element either on the list or its iterator.
  • Arrays.asList: This returns instead a not resizable List, which means that you can replace an element of the list but cannot remove or add any element.

With Java 8, the best option to get the same thing as List.of is to use the static method Collections.unmodifiableList. You can use it just to wrap your list, so every time you try to do any operation on the list or on its iterator (i.e. set, add, remove) an UnsupportedOperationException is thrown. Here is an example related to a List of String.

List<String> newUnmodList = Collections.unmodifiableList(oldList);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest