что значит arrays aslist

Списочный массив ArrayList

Знакомство с ArrayList

Работать с ArrayList просто: создайте нужный объект, вставьте объект методом add(), обращайтесь к нему методом get(), используйте индексирование так же, как для массивов, но без квадратных скобок. ArrayList также содержит метод size(), который возвращает текущее количество элементов в массиве (напомню, что в обычном массиве используется свойство length).

Переменные принято называть во множественном числе.

Рассмотрим на примерах.

Запускаем программу и видим, что в текстовом поле отобразилось имя кота Васьки. Что же произошло? Мы объявили экземпляр класса ArrayList под именем catNames и через метод add() добавили имя. Списочный массив стал содержать одну строку и мы можем в этом убедиться, когда выводим в текстовом поле первый элемент массива через индекс, равный 0.

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

Что теперь произошло? В методе onCreate() как прежде добавляется одно имя, которое выводится в текстовом поле. При нажатии на кнопку мы добавляем ещё два имени, а в текстовой метке выводим имя второго кота через метод catnamesList.get(1).

Хорошо, мы знаем, что добавили трёх котов и поэтому можем обращаться через индекс 0, 1 или 2. А если котов стало слишком много, и мы запутались в их количестве? Тогда нужно вызвать метод size(), который вернёт общее число элементов массива. В этом случае, чтобы получить имя последнего кота в массиве, нужно получить размер массива и отнять единицу.

Вроде бы всё замечательно. Но студия выводит предупреждение у кода метода add(). Почему?

Мы знаем, что у кота есть четыре лапы и хвост. Создадим отдельную переменную для количества лап и попробуем запихнуть их в массив имён. Выглядит как бред, но Java не ругается на наши действия. Вы можете через метод size() убедиться, что размер массива увеличился. Но при попытке вывести последний элемент получим ошибку.

Чтобы вы не совершали подобных ошибок, был придуман следующий подход. Когда вы создаёте новый объект для массива, то в угловых скобках сразу указываете, какой тип собираетесь использовать.

Как только вы исправите пример, то строчка mCatNames.add(paws); будет сразу подчёркнута красной линией. Java поняла, что мы хотим использовать в массиве только строки, а не числа. Поэтому, вы уже не совершите глупых ошибок. Удалите неправильную строку, остальное можно оставить без изменений.

Теперь студия не ругается, и мы можем свернуться калачиком и поспать.

Такая форма записи с угловыми скобками говорит о том, что мы использовали generic-класс (дженерик или обобщение) с типизированными параметрами.

В Java 7 появилась укороченная запись, называемая ромбовидной. Вы можете опустить параметр с правой стороны выражения.

Если у вас есть собственный класс, то он используется таким же образом, только с использованием ключевого слова new.

Метод add()

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

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

Методы ensureCapacity() и trimToSize()

Если заранее известно, сколько элементов следует хранить, то перед заполнением массива вызовите метод ensureCapacity():

Первоначальную ёмкость можно задать и в конструкторе в качестве параметра.

Если вы уверены, что списочный массив будет иметь постоянный размер, то можете использовать метод trimToSize(). Это может способствовать рациональному использованию памяти.

Метод indexOf()

Предположим, мы внимательно следим за Рыжиком. Когда он был последним, то его легко было вычислить. Зная размер массива, мы вычитали единицу и получали к нему доступ. Но потом мы стали добавлять в массив других котов и уже не сможем понять, где теперь наш Рыжик. Но выход всегда есть. Существует метод indexOf(), который ищет подходящий элемент и выводит его индекс.

Не забываем, что отсчёт массива идёт с 0, если индекс равен 2, значит он является третим в массиве.

Просмотр всех элементов через цикл

Чтобы вывести всех усатых-полосатых на чистую воду, используем цикл for:

Или укороченная запись:

Метод contains()

Чтобы узнать, есть в массиве какой-либо элемент, можно воспользоваться методом contains(), который вернёт true или false:

Понятно, что в нашем массиве никаких бобиков и барбосов быть не может, поэтому появится надпись false.

Для удаления элемента из массива используется метод remove(). Можно удалять по индексу или по объекту:

Элементы, следующие после удалённого элемента, сдвигаются влево, а размер списочного массива уменьшается на единицу.

Метод removeAll() удаляет сразу все элементы. Но лучше использовать метод clear().

Чтобы заменить элемент в массиве, нужно использовать метод set() с указанием индекса и новым значением. Предположим, вы обнаружили, что у вас не кот Мурзик, а кошка Мурка. Нет проблем.

Для очистки массива используется метод clear():

Метод работает гораздо быстрее похожего метода removeAll().

Также можно сконвертировать из нашего списка в обычный массив и выполнить другие операции. Читайте документацию.

Конвертация в массив может понадобится для ускорения некоторых операций, передачи массива в качестве параметра методам, которые требуют именно массив и другие причины.

В Java 8 появился ещё один вариант через Stream.

Сколько раз совпадают элементы

В списочном массиве значения вполне могут совпадать. Например, среди котов попадаются однофамильцы и мы их спокойно можем запихнуть в ArrayList. Но сколько раз повторяются одинаковые элементы?

Интерфейс List

java.util.List является интерфейсом и его можно использовать вместо ArrayList следующим образом:

Или укороченный вариант для Java 7:

Как видите, мы заменили ArrayList на List, но при этом в объявлении оставили new ArrayList(). Всё остальное остаётся без изменений. Кстати, этот способ является рекомендуемым. Но иногда он может не подойти.

Контейнеры List гарантируют определённый порядок следования элементов. Интерфейс List дополняет Collection несколькими методами, обеспечивающими вставку и удаление элементов в середине списка.

Существует две основные разновидности List:

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

Метод contains() проверяет, присутствует ли объект в списке. Чтобы удалить объект, передайте ссылку на него методу remove(). Кроме того, если у вас имеется ссылка на объект, вы можете определить индекс объекта в List при помощи метода indexOf().

Сам List реализует более общий интерфейс коллекции Collection и можно было даже написать:

Но у Collection нет методов set() и get(), поэтому работать с таким интерфейсом не очень удобно.

Для создания массива можно не только добавлять по одному объекту через метод add(), но и сразу массив через метод Arrays.asList().

Оставим пока в покое котов и создадим массив из объектов Integer.

Но у данного способа есть недостаток. Если вы определили массив таким образом, то уже не можете вставлять или удалять другой элемент (методы add() и delete()), хотя при этом можете изменять существующий элемент.

В Android 11 (R) обещают добавить несколько перегруженных версий метода of(), которые являются частью Java 8.

Заключение

С ArrayList работать проще и удобнее, чем с массивами. Можно без проблем добавлять новые элементы, в том числе и в середину листа. А в случае использования обычного массива вам придётся заново выделять память и перезаписывать элементы, так как размер массива поменять нельзя, после того как была выделена память.

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

Структура данных в картинках

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

Только что созданный объект list содержит свойства elementData и size.

Хранилище значений elementData есть ни что иное как массив определенного типа (указанного в generic), в нашем случае String[]. Если вызывается конструктор без параметров, то по умолчанию будет создан массив из 10-ти элементов типа Object (с приведением к типу, разумеется).

что значит arrays aslist. Смотреть фото что значит arrays aslist. Смотреть картинку что значит arrays aslist. Картинка про что значит arrays aslist. Фото что значит arrays aslist

Добавим новый элемент:

что значит arrays aslist. Смотреть фото что значит arrays aslist. Смотреть картинку что значит arrays aslist. Картинка про что значит arrays aslist. Фото что значит arrays aslist

Внутри метода add(value) происходят следующие вещи:

1) проверяется, достаточно ли места в массиве для вставки нового элемента;

2) добавляется элемент в конец (согласно значению size) массива.

Если места в массиве не достаточно, новая ёмкость рассчитывается по формуле (oldCapacity * 3) / 2 + 1. Второй момент это копирование элементов. Оно осуществляется с помощью native-метода System.arraycopy(), который написан не на Java.

Ниже продемонстрирован цикл, поочередно добавляющий 15 элементов:

что значит arrays aslist. Смотреть фото что значит arrays aslist. Смотреть картинку что значит arrays aslist. Картинка про что значит arrays aslist. Фото что значит arrays aslist

что значит arrays aslist. Смотреть фото что значит arrays aslist. Смотреть картинку что значит arrays aslist. Картинка про что значит arrays aslist. Фото что значит arrays aslist

При добавлении 11-го элемента, проверка показывает что места в массиве нет. Соответственно создается новый массив и вызывается System.arraycopy().

что значит arrays aslist. Смотреть фото что значит arrays aslist. Смотреть картинку что значит arrays aslist. Картинка про что значит arrays aslist. Фото что значит arrays aslist

После этого добавление элементов продолжается.

что значит arrays aslist. Смотреть фото что значит arrays aslist. Смотреть картинку что значит arrays aslist. Картинка про что значит arrays aslist. Фото что значит arrays aslist

Рассмотрим добавление в «середину» списка.

Добавление элемента на позицию с определенным индексом происходит в три этапа:

1) проверяется, достаточно ли места в массиве для вставки нового элемента;

2) подготавливается место для нового элемента с помощью System.arraycopy();

что значит arrays aslist. Смотреть фото что значит arrays aslist. Смотреть картинку что значит arrays aslist. Картинка про что значит arrays aslist. Фото что значит arrays aslist

3) перезаписывается значение у элемента с указанным индексом.

что значит arrays aslist. Смотреть фото что значит arrays aslist. Смотреть картинку что значит arrays aslist. Картинка про что значит arrays aslist. Фото что значит arrays aslist

Как можно догадаться, в случаях, когда происходит вставка элемента по индексу и при этом в вашем массиве нет свободных мест, то вызов System.arraycopy() случится дважды: первый в ensureCapacity(), второй в самом методе add(index, value), что явно скажется на скорости всей операции добавления.

В случаях, когда в исходный список необходимо добавить другую коллекцию, да еще и в «середину», стоит использовать метод addAll(index, Collection). И хотя, данный метод скорее всего вызовет System.arraycopy() три раза, в итоге это будет гораздо быстрее поэлементного добавления.

Удалять элементы можно двумя способами:

— по индексу remove(index)
— по значению remove(value)

С удалением элемента по индексу всё достаточно просто:

Сначала определяется какое количество элементов надо скопировать:

Затем копируем элементы используя System.arraycopy():

Уменьшаем размер массива и забываем про последний элемент:

При удалении по значению, в цикле просматриваются все элементы списка, до тех пор пока не будет найдено соответствие. Удален будет лишь первый найденный элемент.

При удалении элементов текущая величина capacity не уменьшается, что может привести к своеобразным утечкам памяти. Поэтому не стоит пренебрегать методом trimToSize().

Объединяем два ArrayList

С помощью библиотеки Apache Commons Collections можно объединить два ArrayList.

Сортировка

Сортировать элементы можно при помощи метода Collections.sort().

Интерфейс ListIterator

На практике он мне не встречался. Позволяет проходить по всем элементам вперёд или назад. Для этого он проверяет, есть ли следующий/предыдущий элемент после текущего.

Выводим все элементы от начала до конца, а потом в обратном направлении.

Источник

Разница между массивами.asList (массив) и новый ArrayList (массивы.asList(массив))

в чем разница между

когда я перетасовываю списки, list1 не влияет на исходный массив, но list2 делает. Но все же list2 несколько сбивает с толку.

как ArrayList будучи upcasted в список отличается от создания новых ArrayList

12 ответов

во-первых, давайте посмотрим, что это:

С другой стороны, если вы впоследствии создадите новый массив как

Я довольно поздно здесь, в любом случае чувствовал, что объяснение со ссылками на doc было бы лучше для кого-то, кто ищет ответ.

ArrayList имеет кучу перегруженных конструкторов

публичный ArrayList (коллекция c)

общественного класса ArrayList(тип int initialCapacity)

Итак, когда мы передаем массивы.asList вернул объект, т. е. List (AbstractList) во второй конструктор выше, он создаст новый динамический массив (этот размер массива увеличивается, поскольку мы добавляем больше элементов, чем его емкость, а также новые элементы не повлияют на исходный массив) неглубокое копирование исходного массива (мелкая копия означает, что он копирует только ссылки и не создает новый набор тех же объектов, что и в массиве orignal)

обратите внимание, что в Java 8 ‘ia’ выше должен быть Integer [], а не int[]. Матрицы.asList() массива int возвращает список с одним элементом. При использовании фрагмента кода OP компилятор поймает проблему, но некоторые методы (например, коллекции.shuffle ()) молча не сможет сделать то, что вы ожидаете.

этот метод возвращает свою собственную реализацию списка.Он принимает массив в качестве аргумента и строит методы и атрибуты поверх него, поскольку он не копирует какие-либо данные из массива, но использует исходный массив, что вызывает изменение исходного массива при изменении списка, возвращаемого Arrays.asList() метод.

С другой стороны.
ArrayList(Arrays.asList()); является конструктором ArrayList класс, который принимает список в качестве аргумента и возвращает ArrayList это независимо от списка ie. Arrays.asList() в этом случае передается как аргумент. вот почему вы видите эти результаты;

прежде всего класс Arrays-это класс утилиты, который содержит no. утилитарных методов для работы с массивами (благодаря классу массивов, иначе нам пришлось бы создавать собственные методы для работы с объектами массива)

метод asList ():

в первом случае вы создаете новый Arraylist object (во втором случае создается только ссылка на существующий объект массива, но не новый ArrayList object), поэтому теперь есть два разных объекта, один из которых

вы не можете использовать некоторые операции для строки 2, потому что внутренний частный класс в Arrays не предоставляет эти методы.

строка 1 создает новый ArrayList объект копирования элементов из того, что вы получаете из строки 2. Так что вы можете делать все, что хотите, так как java.util.ArrayList предоставляет все эти методы.

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

когда список создается без использования новых массивов оператора.метод asList () возвращает оболочку, что означает

1. вы можете выполнить операцию добавления/обновления.

2. изменения, сделанные в исходном массиве, также будут отражены в списке и наоборот.

Источник

Что значит arrays aslist

The documentation for the methods contained in this class includes briefs description of the implementations. Such descriptions should be regarded as implementation notes, rather than parts of the specification. Implementors should feel free to substitute other algorithms, so long as the specification itself is adhered to. (For example, the algorithm used by sort(Object[]) does not have to be a MergeSort, but it does have to be stable.)

This class is a member of the Java Collections Framework.

Method Summary

Methods

Modifier and TypeMethod and Description
static ListasList(T. a)
static intbinarySearch(double[] a, int fromIndex, int toIndex, double key)static intbinarySearch(float[] a, int fromIndex, int toIndex, float key)static intbinarySearch(short[] a, int fromIndex, int toIndex, short key)static voidfill(boolean[] a, int fromIndex, int toIndex, boolean val)static voidfill(double[] a, int fromIndex, int toIndex, double val)static voidfill(float[] a, int fromIndex, int toIndex, float val)static voidfill(short[] a, int fromIndex, int toIndex, short val)

Methods inherited from class java.lang.Object

Method Detail

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

Implementation note: This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.

The implementation takes equal advantage of ascending and descending order in its input array, and can take advantage of ascending and descending order in different parts of the the same input array. It is well-suited to merging two or more sorted arrays: simply concatenate the arrays and sort the resulting array.

The implementation was adapted from Tim Peters’s list sort for Python ( TimSort). It uses techiques from Peter McIlroy’s «Optimistic Sorting and Information Theoretic Complexity», in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

Implementation note: This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.

The implementation takes equal advantage of ascending and descending order in its input array, and can take advantage of ascending and descending order in different parts of the the same input array. It is well-suited to merging two or more sorted arrays: simply concatenate the arrays and sort the resulting array.

The implementation was adapted from Tim Peters’s list sort for Python ( TimSort). It uses techiques from Peter McIlroy’s «Optimistic Sorting and Information Theoretic Complexity», in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

Implementation note: This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.

The implementation takes equal advantage of ascending and descending order in its input array, and can take advantage of ascending and descending order in different parts of the the same input array. It is well-suited to merging two or more sorted arrays: simply concatenate the arrays and sort the resulting array.

The implementation was adapted from Tim Peters’s list sort for Python ( TimSort). It uses techiques from Peter McIlroy’s «Optimistic Sorting and Information Theoretic Complexity», in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

Implementation note: This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.

The implementation takes equal advantage of ascending and descending order in its input array, and can take advantage of ascending and descending order in different parts of the the same input array. It is well-suited to merging two or more sorted arrays: simply concatenate the arrays and sort the resulting array.

The implementation was adapted from Tim Peters’s list sort for Python ( TimSort). It uses techiques from Peter McIlroy’s «Optimistic Sorting and Information Theoretic Complexity», in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.

binarySearch

binarySearch

binarySearch

binarySearch

binarySearch

binarySearch

binarySearch

binarySearch

binarySearch

binarySearch

binarySearch

binarySearch

binarySearch

binarySearch

binarySearch

binarySearch

binarySearch

binarySearch

equals

equals

equals

equals

equals

equals

equals

equals

equals

copyOf

copyOf

copyOf

copyOf

copyOf

copyOf

copyOf

copyOf

copyOf

copyOf

copyOfRange

The resulting array is of exactly the same class as the original array.

copyOfRange

copyOfRange

copyOfRange

copyOfRange

copyOfRange

copyOfRange

copyOfRange

copyOfRange

copyOfRange

asList

This method also provides a convenient way to create a fixed-size list initialized to contain several elements:

hashCode

hashCode

hashCode

hashCode

hashCode

hashCode

hashCode

hashCode

hashCode

For any two arrays a and b such that Arrays.equals(a, b), it is also the case that Arrays.hashCode(a) == Arrays.hashCode(b).

The value returned by this method is equal to the value that would be returned by Arrays.asList(a).hashCode(), unless a is null, in which case 0 is returned.

deepHashCode

For any two arrays a and b such that Arrays.deepEquals(a, b), it is also the case that Arrays.deepHashCode(a) == Arrays.deepHashCode(b).

The computation of the value returned by this method is similar to that of the value returned by List.hashCode() on a list containing the same elements as a in the same order, with one difference: If an element e of a is itself an array, its hash code is computed not by calling e.hashCode(), but as by calling the appropriate overloading of Arrays.hashCode(e) if e is an array of a primitive type, or as by calling Arrays.deepHashCode(e) recursively if e is an array of a reference type. If a is null, this method returns 0.

deepEquals

Two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of elements and all corresponding pairs of elements in the two arrays are deeply equal.

If either of the specified arrays contain themselves as elements either directly or indirectly through one or more levels of arrays, the behavior of this method is undefined.

toString

toString

toString

toString

toString

toString

toString

toString

toString

The value returned by this method is equal to the value that would be returned by Arrays.asList(a).toString(), unless a is null, in which case "null" is returned.

deepToString

The string representation consists of a list of the array’s elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(Object), unless they are themselves arrays.

If an element e is an array of a primitive type, it is converted to a string as by invoking the appropriate overloading of Arrays.toString(e). If an element e is an array of a reference type, it is converted to a string as by invoking this method recursively.

To avoid infinite recursion, if the specified array contains itself as an element, or contains an indirect reference to itself through one or more levels of arrays, the self-reference is converted to the string "[. ]". For example, an array containing only a reference to itself would be rendered as "[[. ]]".

This method returns "null" if the specified array is null.

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2020, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *