- Разница между типом List и ArrayList в Java
- Использование интерфейса List
- Использование класса ArrayList
- Заключение
- Java разница list arraylist
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Список против ArrayList в Java
- 2. Использование ArrayList
- 2.1. Быстрый пример
- 2.2. Проблема с данными переменного размера
- 2.3. Изменение типа реализации
- 3. Переключение на список
- 4. Сравнение подходов
- Difference Between List and ArrayList in Java
- What is a List in Java?
- What is an ArrayList in Java?
- Differences: List and ArrayList in Java
- Conclusion
Разница между типом List и ArrayList в Java
При создании коллекций в Java часто возникает вопрос — какой тип использовать для объявления: интерфейс List или конкретный класс ArrayList. Например:
List<String> myList = new ArrayList<String>(); //первый вариант ArrayList<String> myList = new ArrayList<String>(); //второй вариант
Оба этих варианта корректны, но они имеют некоторые различия в использовании.
Использование интерфейса List
Использование интерфейса List для объявления коллекции предоставляет большую гибкость. В любой момент можно легко заменить используемую реализацию коллекции на другую, например, на LinkedList, не изменяя тип переменной. Это особенно полезно, когда реализация коллекции выбирается в зависимости от некоторых условий или может меняться в процессе работы приложения.
List<String> myList = new LinkedList<String>(); //без проблем заменили ArrayList на LinkedList
Использование класса ArrayList
Использование конкретного класса ArrayList для объявления коллекции ограничивает ее реализацию этим конкретным классом. В данном случае, замена на другую реализацию потребует изменения типа переменной.
ArrayList<String> myList = new LinkedList<String>(); //ошибка компиляции
Но при этом класс ArrayList может содержать дополнительные методы, которых нет в интерфейсе List. И если эти методы необходимы в коде, то выбор падает на второй вариант.
Заключение
В большинстве случаев рекомендуется использовать интерфейс List для объявления коллекции, так как это предоставляет больше гибкости и возможностей для изменения кода в будущем. Однако, если используются специфические методы класса ArrayList, то он выбирается в качестве типа переменной.
Java разница list arraylist
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Список против ArrayList в Java
Во-первых, мы увидим пример реализации с использованием ArrayList . Затем мы переключимся на интерфейс списка и сравним различия.
2. Использование ArrayList
ArrayList — одна из наиболее часто используемых реализаций списка в Java. Он построен на основе массива, который может динамически увеличиваться и уменьшаться по мере добавления или удаления элементов. Хорошо инициализировать список начальной емкостью, когда мы знаем, что он станет большим:
ArrayListString> list = new ArrayList>(25);
Используя ArrayList в качестве ссылочного типа, мы можем использовать методы в ArrayList API, которых нет в List API, например, sureCapacity, trimToSize или removeRange .
2.1. Быстрый пример
Давайте напишем базовое приложение для обработки пассажиров:
public class ArrayListDemo private ArrayListPassenger> passengers = new ArrayList>(20); public ArrayListPassenger> addPassenger(Passenger passenger) passengers.add(passenger); return passengers; > public ArrayListPassenger> getPassengersBySource(String source) return new ArrayListPassenger>(passengers.stream() .filter(it -> it.getSource().equals(source)) .collect(Collectors.toList())); > // Few other functions to remove passenger, get by destination, . >
Здесь мы использовали тип ArrayList для хранения и возврата списка пассажиров. Поскольку максимальное количество пассажиров равно 20, исходная вместимость списка установлена на это значение.
2.2. Проблема с данными переменного размера
Вышеупомянутая реализация работает нормально, пока нам не нужно менять тип списка , который мы используем. В нашем примере мы выбрали ArrayList и решили, что он соответствует нашим потребностям.
Однако предположим, что по мере развития приложения становится понятно, что количество пассажиров довольно сильно варьируется. Например, если есть только пять забронированных пассажиров с начальной вместимостью 20, потери памяти составляют 75%. Допустим, мы решили переключиться на более эффективный по памяти список .
2.3. Изменение типа реализации
Java предоставляет еще одну реализацию списка , называемую LinkedList , для хранения данных переменного размера . LinkedList использует набор связанных узлов для хранения и извлечения элементов. Что, если мы решили изменить базовую реализацию с ArrayList на LinkedList :
private LinkedListPassenger> passengers = new LinkedList>();
Это изменение затрагивает больше частей приложения, поскольку предполагается, что все функции в демонстрационном приложении будут работать с типом ArrayList .
3. Переключение на список
Давайте посмотрим, как мы можем справиться с этой ситуацией, используя тип интерфейса List :
private ListPassenger> passengers = new ArrayList>(20);
Здесь мы используем интерфейс List в качестве ссылочного типа вместо более конкретного типа ArrayList . Мы можем применить тот же принцип ко всем вызовам функций и типам возвращаемых значений. Например:
public ListPassenger> getPassengersBySource(String source) return passengers.stream() .filter(it -> it.getSource().equals(source)) .collect(Collectors.toList()); >
Теперь рассмотрим ту же постановку задачи и изменим базовую реализацию на тип LinkedList . Классы ArrayList и LinkedList являются реализациями интерфейса List . Итак, теперь мы можем безопасно изменить базовую реализацию, не создавая помех другим частям приложения. Класс по-прежнему компилируется и работает нормально, как и раньше.
4. Сравнение подходов
Если мы используем конкретный тип списка во всей программе, то весь наш код будет без необходимости связан с этим типом списка. Это усложняет изменение типов списков в будущем.
Кроме того, служебные классы, доступные в Java, возвращают абстрактный тип, а не конкретный тип. Например, приведенные ниже служебные функции возвращают тип List :
Collections.singletonList(...), Collections.unmodifiableList(...)
Difference Between List and ArrayList in Java
A collection framework in Java consists of a set of classes and interfaces which helps in implementing various data structures. List and ArrayList belong to this collection framework. List is an interface and ArrayList is a class. Their main motto is to create a list data structure. List is a collection of ordered elements arranged using the concept of indexing. Arrays use the concept of dynamic array to store elements.
What is a List in Java?
A list is one of the interfaces of the collection framework. It stores objects in an ordered manner. Here, the elements are stored sequentially. A list allows duplicate values to store in it. In Lists, elements insertion, deletion, update and search operations are carried out using index-based method. As it preserves the index of the elements stored, it is easy to access them.
You can use a List interface with the help of java.util package. List interface can be implemented by the classes like LinkedList, ArrayList, vector, stack, etc. These classes are used to implement the concept of listing in Java. ListIterator classes are also based on this List which enable us to iterate through the list. The instances of this interface are created using those classes.
Each and every element in a list has an index. Using this index, it become easy to access that element. This indexing of elements starts with Zero. Along with the methods inherited in collection framework, Lists also have their own methods. They are «add (int, E)» and «addAll (int, collection)». These methods are used to add an element into the list based on their index. It also has get(), set(), and sublist() methods used to access the elements, set the value, and to create a sublist of the given list.
What is an ArrayList in Java?
An ArrayList is an extension of abstract class that implements the List interface. ArrayList is similar to that of an array except that its size increases and decreases automatically whenever the elements are added or removed from it. It follows the concept of dynamic array. An Arraylist can store same or different elements.
Using ArrayList, we can insert, update, delete elements at any index. Insertion and deletion operations in ArrayList are slower than that of List. When we insert a new element to an existing ArrayList, the elements below that are shifted to the next index. Similarly, deletion of an element leads to shifting of elements to the previous indexes which is a time taking process.
ArrayList is best for searching operation. It fetches the results faster. Its indexing also starts from zero.
ArrayList has methods to perform various operations. Some of them are −
- add() − used to add elements into ArrayList
- get() − used to access an element
- set() − used to modify an existing element
- remove() − used to delete or remove an element from ArrayList
- clear() − used to clear all elements in an ArrayList
Here are some of the advantages of using ArrayLists −
- ArrayLists have dynamic size. They automatically increase or decrease their size based on the elements entered.
- ArrayLists can store null elements in them. They also allow duplicate values.
- One can insert or delete elements from a particular index.
- We can easily access elements from a desired index
- ArrayLists can store multiple data types.
- ArrayLists provide various methods to manipulate the elements present in them. Elements can be accessed in both forward and from backward directions
Following are some of the disadvantages of using ArrayLists −
- Inserting or deleting an element in an ArrayList is a slow process, as it involves complete shifting of data in them
- ArrayLists can’t hold primitive data types such as int, float, etc. They can only hold object types
Differences: List and ArrayList in Java
The following table highlights the major differences between List and ArrayList in Java −
List is an interface of the collection framework
ArrayList is one of the class that implements List interface
It extends the collection framework
It extends the Abstract class
Lists create a list of elements that can be accessed using indexes
ArrayLists create dynamic arrays that can also be accessed using their indexes
System.Collection.Generic is the namespace for List interface
System.collection is the namespace for ArrayList
It is used to create an ordered list of elements which can be accessed using their indexes
It is used to create a dynamic array of elements
Insert and delete operations are faster in list than that of ArrayList
Insert and delete operations are slower in ArrayLisst
Searching is slower in List
It allows faster searching of an element
A List can’t be instantiated
An ArrayList can be instantiated
Conclusion
A list is an interface of the collection framework, whereas an ArrayList is a class which is used to implement the concept of lists. ArrayLists are widely used due to their dynamic nature. Normal arrays can store values of only a single data type which is not the case with ArrayLists. ArrrayList can store values of different data types.