What is final arraylist in java

Can we have final ArrayList in Java?

I f you want a final (immutable) ArrayList go for Collections class’s utility method Collections. unmodifaibleList( list ) instead. The final arrayList can still be modified, refer to the example below and run it to see for your self. As you can see, the main method is adding (modifying) the list.

What is final ArrayList in Java?

You’re right that declaring the list final means that you cannot reassign the list variable to another object. final as you know means that you cannot reassign the list variable another value.

Can list be final in Java?

6 Answers. No, the final keyword does not make the list, or its contents immutable. If you want an immutable List, you should use: List unmodifiableList = Collections.

How do you create a final array in Java?

In Java an array is an object. This same thing applies to any other object: final List myList = new ArrayList(): myList = anotherList; // error, you can’t do that myList. add(“Hi there!”); // perfectly fine.

What is final variable in Java?

From Wikipedia, the free encyclopedia. In the Java programming language, the final keyword is used in several contexts to define an entity that can only be assigned once. Once a final variable has been assigned, it always contains the same value.

What is the use of final class in Java?

The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class. You cannot extend a final class.

What is final object in Java?

final : In Java, final is a modifier which is used for class, method and variable also. When a variable is declared with final keyword, it’s value can’t be modified, essentially, a constant. In Java, we know that String objects are immutable means we cant change anything to the existing String objects.

How do you use final class?

There are two uses of a final class: Usage 1: One is definitely to prevent inheritance, as final classes cannot be extended. For example, all Wrapper Classes like Integer, Float, etc. are final classes.

How to create an ArrayList in Java?

How to create an array in Java?

How to declare an ArrayList?

How to create list of lists in Java?

Источник

в чем смысл final ArrayList?

Какие преимущества / недостатки мы можем получить, сделав ArrayList (или другую коллекцию) окончательной? Я все еще могу добавлять в ArrayList новые элементы, удалять элементы и обновлять его. Но какой эффект делает его окончательным?

Когда массив объявлен как окончательный, состояние объекта, хранящегося в массиве, может быть изменено. Вам нужно сделать его неизменяемым, чтобы не допускать модификаций.

Читайте также:  Java char into int

13 ответов

Но какой эффект делает его окончательным?

Это означает, что вы не можете повторно привязать переменную, чтобы она указывала на другой экземпляр коллекции :

final List list = new ArrayList(); list = new ArrayList(); // Since `list' is final, this won't compile 

Что касается стиля, я объявляю большинство ссылок, которые я не собираюсь изменять, как final .

Я все еще могу добавлять в ArrayList новые элементы, удалять элементы и обновлять его.

При желании вы можете предотвратить вставку, удаление и т. Д. С помощью Collections.unmodifiableList() :

final List list = Collections.unmodifiableList(new ArrayList(. )); 

+1 Использование финальных полей может улучшить ясность, так как классы могут быть довольно длинными. Я не использую final в методах так часто, как пытаюсь разбить длинные методы.

Это просто означает, что вы не можете переназначить его ссылку. Попытка сделать что-то подобное приведенному ниже приведет к ошибке компилятора.

final List list = new ArrayList(); list = new LinkedList(); ^ Compiler error here 

Если вам действительно нужен неизменяемый список, вы должны использовать метод Collections.unmodifiableList() .

Вы не сможете изменить его ссылку, например, с помощью new ArrayList .

Это не влияет на то, что вы можете делать с ArrayList, как вы правильно заметили — сам ArrayList все еще изменяемый. Вы только что сделали ссылку неизменной.

Но создание переменной final имеет и другие преимущества:

  • Это предотвращает изменение переменной, если ожидается, что она останется постоянной. Это может помочь предотвратить будущие ошибки.
  • Создание переменных final может помочь компилятору оптимизировать производительность.

В общем, чем больше вещей вы сделаете неизменными, тем лучше. Так что сделать ссылки окончательными (даже если они являются ссылками на изменяемые объекты), как правило, является хорошей идеей.

Final — это ключевое слово или зарезервированное слово в java, которое может применяться к переменным-членам, методам, классам и локальным переменным в Java. После того, как вы сделаете ссылку final, вам не разрешено изменять эту ссылку, и компилятор проверит это и вызовет ошибку компиляции, если вы попытаетесь повторно инициализировать конечные переменные в java.

Вы не можете повторно привязать его к другой коллекции, как сказал aix.

Пример: в сочетании с реализацией неизменяемого списка вы получаете безопасные члены, которые можно сделать общедоступными.

Пример: когда вы полагаетесь на то, что ссылка не меняется, вам нужен final. Это верно, например, в сценариях синхронизации.

Примеров может быть гораздо больше. Если вы вообще не собираетесь менять ссылку, это хороший стиль.

Чтобы получить действительно неизменяемый список, вам нужно будет сделать глубокие копии содержимого списка. UnmodifiableList только сделает список ссылок несколько неизменным. Теперь создание глубокой копии списка или массива будет затруднительно для памяти с растущим размером. Вы можете использовать сериализацию / десериализацию и сохранить глубокую копию массива / списка во временном файле. Установщик не будет доступен, поскольку переменная-член должна быть неизменной. Получатель сериализует переменную-член в файл, а затем десиализует ее, чтобы получить полную копию. Сераизация имеет врожденную природу проникновения в глубины дерева объектов. Однако это обеспечит полную неизменяемость при некоторой потере производительности.

 package com.home.immutable.serial; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; public final class ImmutableBySerial < private final int num; private final String str; private final ArrayListimmutableList; ImmutableBySerial(int num, String str, ArrayList list) < this.num = num; this.str = str; this.immutableList = getDeepCloned(list); >public int getNum() < return num; >public String getStr() < return str; >public ArrayList getImmutableList() < return getDeepCloned(immutableList); >private ArrayList getDeepCloned(ArrayList list) < FileOutputStream fos = null; ObjectOutputStream oos = null; FileInputStream fis = null; ObjectInputStream ois = null; ArrayListclonedObj = null; try < fos = new FileOutputStream(new File("temp")); oos = new ObjectOutputStream(fos); oos.writeObject(list); fis = new FileInputStream(new File("temp")); ois = new ObjectInputStream(fis); clonedObj = (ArrayList)ois.readObject(); > catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >catch (ClassNotFoundException e) < e.printStackTrace(); >finally < try < oos.close(); fos.close(); >catch (IOException e) < e.printStackTrace(); >> return clonedObj; > > 

Я лично помечаю поле коллекций моих классов как final , чтобы уберечь пользователей моего класса от проверки, является ли оно нулевым или нет. Это работает, потому что, если значение уже присвоено конечной переменной, его нельзя переназначить другому значению, включая null.

Читайте также:  Программа питон для программирования на русском языке

По сути, то, что вы пытаетесь здесь достичь, — это сделать список неизменным, я думаю. Однако, когда вы помечаете ссылку на список как окончательную, это означает, что ссылка не может быть указана на какой-либо другой объект списка, кроме этого.

Если вам нужен окончательный (неизменяемый) список ArrayList, используйте служебный метод класса Collections.unmodifaibleList (list).

Я подумал об этом же вопросе и закодировал пример, чтобы добавить его к объяснению с еще одной точки зрения.

Окончательный список arrayList все еще можно изменить, обратитесь к приведенному ниже примеру и запустите его, чтобы убедиться в этом сами.

Вот неизменный класс с неизменяемым объявлением списка:

public final class ImmutableClassWithArrayList < final ListtheFinalListVar = new ArrayList(); > 

А вот и драйвер:

public class ImmutableClassWithArrayListTester < public static void main(String[] args) < ImmutableClassWithArrayList immClass = new ImmutableClassWithArrayList(); immClass.theFinalListVar.add("name"); immClass.theFinalListVar.forEach(str ->System.out.println(str)); > > 

Как видите, основной метод — это добавление (изменение) списка. Поэтому единственное, что следует отметить, — это то, что «ссылку» на объект типа коллекции нельзя переназначить другому подобному объекту. Как и в ответе adarshr выше, вы не можете использовать immClass.theFinalListVar = new ArrayList (); в основном методе здесь.

Часть модификации действительно помогла мне понять это и надеюсь, что это поможет так же.

Создание переменной final гарантирует, что вы не сможете повторно назначить эту ссылку на объект после ее назначения. Как вы упомянули, вы все еще можете использовать этот список методов для внесения изменений.

Если вы объедините ключевое слово final с использованием Collections.unmodifiableList, вы получите поведение, которого, вероятно, пытаетесь достичь, например:

final List fixedList = Collections.unmodifiableList(someList); 

В результате список, на который указывает fixedList , не может быть изменен. Помните, однако, что его все еще можно изменить с помощью ссылки someList (поэтому убедитесь, что она выходит за рамки после этого присвоения).

final имеет множество последствий при многопоточности.

Что четко не определено, так это:

  1. Компиляторы могут свободно переупорядочивать их, преодолевая барьеры памяти.
  2. Компиляторы всегда могут прочитать кэшированную копию.

Если мы объявим ArrayList окончательным, мы все равно сможем добавлять в него элементы, но не можем переназначить его.

final ArrayList list = new ArrayList<>(); list.add("abc"); //allowed list.add("pqr"); //allowed list = new ArrayList<>(); // Not allowed 

Источник

Читайте также:  User Login

Class ArrayList

Type Parameters: E — the type of elements in this list All Implemented Interfaces: Serializable , Cloneable , Iterable , Collection , List , RandomAccess Direct Known Subclasses: AttributeList , RoleList , RoleUnresolvedList

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null . In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector , except that it is unsynchronized.)

The size , isEmpty , get , set , iterator , and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be «wrapped» using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

List list = Collections.synchronizedList(new ArrayList(. ));

The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

Источник

Оцените статью