With Java 10, we now also have the possibility to create immutable copies of collections. Unmodifiable = Code language: Java ( java ) pyOf(), Set.copyOf(), and Map.copyOf() This is because the wrapper does not contain a copy of the list, but a view: list.add( 4) All subsequent changes to it are also visible in the wrapper. However, the wrapper does not prevent us from modifying the underlying list. If we now try to add an element via the wrapper, we get an UnsupportedOperationException: unmodifiable.add( 4) Įxception in thread "main" Īt java.base/$UnmodifiableCollection.add(.) List unmodifiable = Collections.unmodifiableList(list) Code language: Java ( java ) Here is an example: List list = new ArrayList() With the methods Collections.unmodifiableList(), unmodifiableSet(), unmodifiableMap(), unmodifiableCollection() – and four further variants for sorted and navigable sets and maps – the Java Collections Framework offers the possibility to create unmodifiable wrappers for collection classes. (Local-Variable Type Inference is defined in JDK Enhancement Proposal 286.) Immutable Collections Most importantly, agree on a consistent usage within your team. Is it an int? A String? An enum? A complex value object? Or even a JPA entity from the database?įor a more detailed essay on when to use var and when not to, see the official style guidelines. Otherwise, I can't tell offhand what getStatus() returns. In line 5, I would stick with the old notation.But I also understand if teams decide otherwise. In line 2, var is only minimally shorter than String – so I would rather use String here, too.In line 1, you don't save a single character here, I would stick with int.In the following cases, on the other hand, I would refrain from using var: List.of() and HttpClient.newBuilder().build() – let me clearly see the data type. The classic notation is much longer in both cases. In the example above, this would be the case in lines 3 and 4 (for List and HttpClient). I use it if it is a) significantly shorter and b) I can clearly see the data type in the code. To what extent you use var will probably lead to lengthy discussions in many teams. Status status = getStatus() Code language: Java ( java ) HttpClient httpClient = HttpClient.newBuilder().build() Var status = getStatus() Code language: Java ( java )įor comparison – this is how the definitions look in classic notation: int i = 10 Var httpClient = HttpClient.newBuilder().build() This allows, for example, the following definitions: var i = 10 Since Java 10, we can use the keyword var to declare local variables ( local means: within methods). 9 Conclusion Local-Variable Type Inference ("var")
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |