Progress28.ru

IT Новости


09ae9cb0
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java arrays class

Вводный курс. Язык программирования Java

11. Класс Arrays. Работа с массивами

Большая часть методов работы с массивами определена в специальном классе Arrays пакета java.util. Ряд методов определены в классах java.lang.Object и java.lang.System.

На практике наиболее часто в основном используются методы класса java.util.Arrays, а также несколько методов классов java.lang.Object и java.lang.System. Указанные методы представлены ниже.

Методы перегружены для всех примитивных типов

[]b=Arrays.copyOf([]a, int newLength)

[]a – исходный массив

[]b – новый массив

newLength – длина нового массива

[]b=Arrays.copyOfRange ([]a, int index1, int index2)

копирование части массива,

[]a – исходный массив

[]b – новый массив

index1, index2– начальный и конечный индексы копирования

java.lang.System.arraycopy([] a, indexA , []b, indexB, count)

[]a – исходный массив

[]b – новый массив

indexA-начальный индекс копирования исходного массива

indexB-начальный индекс нового массива

count— количество элементов копирования

[]b= a.java.lang.Object.clone()

[]a – исходный массив

[]b – новый массив

Arrays.sort([]a)

Сортировка. Упорядочивание всего массива в порядке возрастания

Arrays.sort([]a,index1,index2)

Сортировка части массива

в порядке возрастания

Arrays.sort([]a, Collections.reverseOrder());

Сортировка. Упорядочивание всего массива в порядке убывания

Boolean f=Arrays.equals([]a,[]b)

String str=Arrays.toString([]a);

Вывод одномерных массивов. Все элементы представлены в виде одной строки

int index=Arrays.binarySearch([]a,элемент a)

поиск элемента методом бинарного поиска

Arrays.fill([]a, элемент заполнения)

заполнение массива переданным значением

Boolean f=Arrays.deepEquals([]a, []b)

сравнение двумерных массивов

List Arrays.asList( []a);

Перевод массива в коллекцию

Для работы с классом необходимо подключить библиотеку java.util.Arrays.

Методы работы с массивами

Копирование массивов

Метод java.util.Arrays.copyOf()

Arrays.copyOf возвращает массив-копию новой длины. Если новая длина меньше исходной, то массив усекается до этой длины, а если больше, то дополняется значениями по умолчанию соответствующего типа.

[]b=Arrays.copyOf([]a, int newLength),

[]a – исходный массив

[]b – новый массив

newLength – длина нового массива

Пример 1.

длина массива a:6
длина массива b: 6
массив a
0.0 1.0 2.0 3.0 4.0 5.0
новая длина массива b: 3
массив b
0.0 1.0 2.0

Пример 2.

массив flag1
true true true
массив flag2
false false false false false
длина массива flag2: 5
массив flag2
true true true false false

Метод java.util. Arrays.copyOf()

Arrays.copyOfRange возвращает массив-копию новой длины, при этом копируется часть оригинального массива от начального индекса до конечного –1.

[]b=Arrays.copyOfRange ([]a, int index1, int index2),

[]a – исходный массив

[]b – новый массив

index1, index2– начальный и конечный индексы копирования

Пример.

Дни недели:
Понедельник Вторник Среда Четверг Пятница Суббота Воскресенье
Рабочие дни
Понедельник Вторник Среда Четверг Пятница

Метод arraycopy() из класса System

Быстродействие метода System.arraycopy() выше по сравнению с использованием цикла for для выполнения копирования. Метод System.arraycopy( ) перегружен для обработки всех типов.

java.lang.System.arraycopy([] a, indexA , []b, indexB, count),

[]a – исходный массив

[]b – новый массив

indexA-начальный индекс копирования исходного массива

indexB-начальный индекс нового массива

count— количество элементов копирования

Пример.

Пример.

Метод clone() из класса Object

[]b= a.java.lang.Object.clone();

[]a – исходный массив

[]b – новый массив

Пример.

Сортировка массивов

Метод Arrays.sort([]a)

Метод sort() из класса Arrays использует усовершенствованный алгоритм Быстрой сортировки (Quicksort), который эффективен для большинства набора данных. Метод упорядочивает весь массив в порядке возрастания значений элементов.

Arrays.sort([]a),

[]a – исходный массив, после работы метода массив будет содержать упорядоченные значения элементов в порядке возрастания.

Пример.

Метод Arrays.sort([]a,index1,index2)

выполняет сортировку части массива по возрастанию массива от index1 до index2 минус единица

Arrays.sort([]a,index1,index2),

[]a – исходный массив

index1, index2 — начальный и конечный индексы, определяющие диапазон упорядочивания элементов по возрастанию.

Сортировка массива по убыванию

Arrays.sort([]a, Collections.reverseOrder());

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

15,39 1,54 17,47 15,50 3,83 16,43 18,87 15,54 8,23 12,97

Массив,отсотированный по убыванию

18,87 17,47 16,43 15,54 15,50 15,39 12,97 8,23 3,83 1,54

Сравнение массивов

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

Класс Object имеет метод equals , который наследуется массивами и не является перегруженным и сравнение идет по адресам объектов, а не по содержимому. Метод equals перегружен только в классе Arrays . Отсюда вытекает правило сравнения массивов:

  • a == b сравниваются адреса массивов
  • a.equals(b) сравниваются адреса массивов
  • Arrays.equals(a, b) сравнивается содержимое массивов
  • Arrays.deepEquals(a, b) сравнивается содержимое многомерных массивов

Boolean f=Arrays.equals([]a,[]b);

Метод вернет true, если содержимое массивов равно, в противном случае false.

Вывод одномерных массивов

Имеется достаточно удобный метод вывода данных одномерного массива — Arrays.toString([]a, который возвращает строковое представление массива со строковым представлением элементов, заключенных в квадратные скобки.

String str=Arrays.toString([]a);

Это адрес: [Ljava.lang.String;@1db9742

Это значения: [Красный, Синий, Зеленый]

До сортировки: [7, 2, 9, 1, 0, 3, 4, 8, 5, 6]

После сортировки: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Вывод многомерных массивов

Для вывода многомерных массивов метод Arrays.deepToString.

String str= Arrays.deepToString([][]a);

массив a: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

массив ch: [[а, б, в], [г, д, е], [ё, ж, з]]

Бинарный поиск элемента в одномерном массиве

Бинарный поиск – алгоритм поиска элемента в отсортированном массиве. Алгоритм основывается на принципе последовательного деления массива пополам.

int index=Arrays.binarySearch([]a,элемент x),

х — искомое значение

index – индекс элемента в массиве, если поиск успешный,

отрицательное число – если в массиве элемент не найден

Массив должен быть отсортирован! В противном случае результат будет неопределенным.

Массив= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

искомое значение = 5

Массив= [август, апрель, декабрь, июль, июнь, май, март, ноябрь, октябрь, сентябрь, февраль, январь]

искомое значение = март

Заполнение массива

Метод Arrays.fill() позволяет заполнить массив одинаковыми данными.

Имеется два метода

Arrays.fill([]a, value);

Arrays.fill(a[], int index1, int index2, value),

[]a – заполняемый массив,

index1, index2- индексы диапазона заполнения,

До заполнения a: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

До заполнения b: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

До заполнения bool: [false, false, false, false, false, false, false, false, false, false]

Читать еще:  Служба проверки сертификатов недоступна ошибка 0x000000ff

После заполнения a: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

После заполнения b: [0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 2.0, 2.0, 2.0, 2.0]

После заполнения: bool[true, true, true, true, true, false, false, false, false, false]

Java.util.Arrays Class

Introduction

The java.util.Arrays class contains a static factory that allows arrays to be viewed as lists.Following are the important points about Arrays −

This class contains various methods for manipulating arrays (such as sorting and searching).

The methods in this class throw a NullPointerException if the specified array reference is null.

Class declaration

Following is the declaration for java.util.Arrays class −

>

Sr.No.Method & Description1static List asList(T. a)

This method returns a fixed-size list backed by the specified array.

This method searches the specified array of bytes for the specified value using the binary search algorithm.

This method searches a range of the specified array of bytes for the specified value using the binary search algorithm.

This method searches the specified array of chars for the specified value using the binary search algorithm.

This method searches a range of the specified array of chars for the specified value using the binary search algorithm.

This method searches the specified array of doubles for the specified value using the binary search algorithm.

This method searches a range of the specified array of doubles for the specified value using the binary search algorithm.

This method searches the specified array of floats for the specified value using the binary search algorithm.

This method searches a range of the specified array of floats for the specified value using the binary search algorithm.

This method searches the specified array of ints for the specified value using the binary search algorithm.

This method searches a range of the specified array of ints for the specified value using the binary search algorithm.

This method searches a range of the specified array of longs for the specified value using the binary search algorithm.

This method searches the specified array of longs for the specified value using the binary search algorithm.

This method searches a range of the specified array for the specified object using the binary search algorithm.

This method searches the specified array for the specified object using the binary search algorithm.

This method searches a range of the specified array of shorts for the specified value using the binary search algorithm.

This method searches the specified array of shorts for the specified value using the binary search algorithm.

This method searches a range of the specified array for the specified object using the binary search algorithm.

This method searches the specified array for the specified object using the binary search algorithm.

This method copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.

This method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.

This method copies the specified array, truncating or padding with null characters (if necessary) so the copy has the specified length.

This method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.

This method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.

This method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.

This method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.

This method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.

This method copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length.

This method copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length.

This method copies the specified range of the specified array into a new array.

This method copies the specified range of the specified array into a new array.

This method copies the specified range of the specified array into a new array.

This method copies the specified range of the specified array into a new array.

This method copies the specified range of the specified array into a new array.

This method copies the specified range of the specified array into a new array.

This method copies the specified range of the specified array into a new array.

This method copies the specified range of the specified array into a new array.

This method copies the specified range of the specified array into a new array.

This method copies the specified range of the specified array into a new array.

This method returns true if the two specified arrays are deeply equal to one another.

This method returns a hash code based on the «deep contents» of the specified array.

This method returns a string representation of the «deep contents» of the specified array.

This method returns true if the two specified arrays of booleans are equal to one another.

This method returns true if the two specified arrays of bytes are equal to one another.

This method returns true if the two specified arrays of chars are equal to one another.

This method returns true if the two specified arrays of doubles are equal to one another.

This method returns true if the two specified arrays of floats are equal to one another.

This method returns true if the two specified arrays of ints are equal to one another.

This method returns true if the two specified arrays of longs are equal to one another.

This method returns true if the two specified arrays of Objects are equal to one another.

This method returns true if the two specified arrays of shorts are equal to one another.

This method assigns the specified boolean value to each element of the specified array of booleans.

This method assigns the specified boolean value to each element of the specified range of the specified array of booleans.

This method assigns the specified byte value to each element of the specified array of bytes.

This method assigns the specified byte value to each element of the specified range of the specified array of bytes.

This method assigns the specified char value to each element of the specified array of chars.

This method assigns the specified char value to each element of the specified range of the specified array of chars.

This method assigns the specified double value to each element of the specified array of doubles.

This method assigns the specified double value to each element of the specified range of the specified array of doubles.

This method assigns the specified float value to each element of the specified array of floats.

This method assigns the specified float value to each element of the specified range of the specified array of floats.

This method assigns the specified int value to each element of the specified array of ints.

This method assigns the specified int value to each element of the specified range of the specified array of ints.

This method assigns the specified long value to each element of the specified range of the specified array of longs.

This method assigns the specified long value to each element of the specified array of longs.

This method assigns the specified Object reference to each element of the specified range of the specified array of Objects.

This method assigns the specified Object reference to each element of the specified array of Objects.

This method assigns the specified short value to each element of the specified range of the specified array of shorts.

This method assigns the specified short value to each element of the specified array of shorts.

This method returns a hash code based on the contents of the specified array.

This method returns a hash code based on the contents of the specified array.

This method returns a hash code based on the contents of the specified array.

This method returns a hash code based on the contents of the specified array.

This method returns a hash code based on the contents of the specified array.

This method returns a hash code based on the contents of the specified array.

This method returns a hash code based on the contents of the specified array.

This method returns a hash code based on the contents of the specified array.

This method returns a hash code based on the contents of the specified array.

This method sorts the specified array of bytes into ascending numerical order.

This method sorts the specified range of the specified array of bytes into ascending numerical order.

This method sorts the specified array of chars into ascending numerical order.

This method sorts the specified range of the specified array of chars into ascending numerical order.

This method sorts the specified array of doubles into ascending numerical order.

This method sorts the specified range of the specified array of doubles into ascending numerical order.

This method sorts the specified array of floats into ascending numerical order.

This method sorts the specified range of the specified array of floats into ascending numerical order.

This method sorts the specified array of ints into ascending numerical order.

This method sorts the specified range of the specified array of ints into ascending numerical order.

This method sorts the specified array of longs into ascending numerical order.

This method sorts the specified range of the specified array of longs into ascending numerical order.

This method sorts the specified array of objects into ascending order, according to the natural ordering of its elements.

This method sorts the specified range of the specified array of objects into ascending order, according to the natural ordering of its elements.

This method sorts the specified array of shorts into ascending numerical order.

This method sorts the specified range of the specified array of shorts into ascending numerical order.

This method sorts the specified array of objects according to the order induced by the specified comparator.

This method sorts the specified range of the specified array of objects according to the order induced by the specified comparator.

This method returns a string representation of the contents of the specified array of boolean.

This method returns a string representation of the contents of the specified array of bytes.

This method returns a string representation of the contents of the specified array of chars.

This method returns a string representation of the contents of the specified array of doubles.

This method returns a string representation of the contents of the specified array of floats.

This method returns a string representation of the contents of the specified array of ints.

This method returns a string representation of the contents of the specified array of longs.

This method returns a string representation of the contents of the specified array of ints.

This method returns a string representation of the contents of the specified array of shorts.

Methods inherited

This class inherits methods from the following classes −

Массивы в Java — определение и создание, инициализация и заполнение

Массив — это структура данных, которая предназначена для хранения однотипных данных. Массивы в Java работают иначе, чем в C/C++. Особенности:

  • Поскольку массивы являются объектами, мы можем найти их длину. Это отличается от C/C++, где мы находим длину с помощью sizeof.
  • Переменная массива может также быть объявлена как другие переменные.
  • Переменные упорядочены и имеют индекс, начинающийся с 0.
  • Может также использоваться как статическое поле, локальная переменная или параметр метода.
  • Размер массива должен быть задан значением int, а не long или short.
  • Прямым суперклассом типа массива является Object.
  • Каждый тип массива реализует интерфейсы Cloneable and java.io.Serializable.

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

В этой статье вы узнаете

Инициализация и доступ к массиву

Одномерные Массивы: общая форма объявления

Объявление состоит из двух компонентов: типа и имени. type объявляет тип элемента массива. Тип элемента определяет тип данных каждого элемента.

Кроме типа int, мы также можем создать массив других типов данных, таких как char, float, double или определяемый пользователем тип данных (объекты класса).Таким образом, тип элемента определяет, какой тип данных будет храниться в массиве. Например:

Хотя приведенное выше первое объявление устанавливает тот факт, что intArray является переменной массива, массив фактически не существует. Он просто говорит компилятору, что эта переменная типа integer.

Чтобы связать массив int с фактическим физическим массивом целых чисел, необходимо обозначить его с помощью new и назначить int.

Как создать массив в Java

При объявлении массива создается только ссылка на массив. Чтобы фактически создать или предоставить память массиву, надо создать массив следующим образом: общая форма new применительно к одномерным и выглядит следующим образом:
var-name = new type [size];

Здесь type указывает тип данных, size — количество элементов в массиве, а var-name-имя переменной массива.

Важно знать, что элементы массива, выделенные функцией new, автоматически инициализируются нулем (для числовых типов), ложью (для логических типов) или нулем (для ссылочных типов).
Получение массива — это двухэтапный процесс. Во-первых, необходимо объявить переменную нужного типа. Во-вторых, необходимо выделить память, которая будет содержать массив, с помощью new, и назначить ее переменной. Таким образом, в Java все массивы выделяются динамически.

Литералы массива

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

  • Длина этого массива определяет длину созданного массива.
  • Нет необходимости писать int[] в последних версиях Java

Доступ к элементам массива Java с помощью цикла for

Доступ к каждому элементу массива осуществляется через его индекс. Индекс начинается с 0 и заканчивается на (общий размер)-1. Все элементы могут быть доступны с помощью цикла for.

// Пример для иллюстрации создания array
// целых чисел, помещает некоторые значения в массив,
// и выводит каждое значение.

class GFG
<
public static void main (String[] args)
<
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.
arr = new int[5];

// initialize the first elements of the array
arr[0] = 10;

// initialize the second elements of the array
arr[1] = 20;

//so on…
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array
for (int i = 0; i  

Массивы объектов

Массив объектов создается так же, как элементов данных следующим образом:

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

// Java program to illustrate creating an array of
// objects

class Student
<
public int roll_no;
public String name;
Student(int roll_no, String name)
<
this.roll_no = roll_no;
this.name = name;
>
>

// Elements of array are objects of a class Student.
public class GFG
<
public static void main (String[] args)
<
// declares an Array of integers.
Student[] arr;

// allocating memory for 5 objects of type Student.
arr = new Student[5];

// initialize the first elements of the array
arr[0] = new Student(1,»aman»);

// initialize the second elements of the array
arr[1] = new Student(2,»vaibhav»);

// so on…
arr[2] = new Student(3,»shikar»);
arr[3] = new Student(4,»dharmesh»);
arr[4] = new Student(5,»mohit»);

// accessing the elements of the specified array
for (int i = 0; i

Многомерные

Многомерные массивы — это массивы массивов, каждый элемент которых содержит ссылку на другой массив. Создается путем добавления одного набора квадратных скобок ([]) для каждого измерения. Рассмотрим пример:

class multiDimensional
<
public static void main(String args[])
<
// declaring and initializing 2D array
int arr[][] = < <2,7,9>,<3,6,1>, <7,4,2>>;

// printing 2D array
for (int i=0; i 

Передача массивов в метод

Как и переменные, мы можем передавать массивы в методы.

На выходе получим:

sum of array values : 15

Возврат массивов из методов

Как обычно, метод также может возвращать массив. Например, ниже программа возвращает массив из метода m1.

Объекты класса

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

class [I
class java.lang.Object
class [B
class [S
class [Ljava.lang.String;

Теперь, как вы знаете, что массивы являются объектом класса. Членами массива являются следующие элементы:

  • Конечная длина открытого поля, содержащего количество компонентов. Длина может быть положительной или нулевой.
  • Все члены наследуются от класса Object; единственный метод объекта, который не наследуется, является метод clone.
  • Открытый метод clone () переопределяет метод clone в объекте класса.

Клонирование массивов

При клонировании одномерного массива, например Object[], выполняется копия с новым массивом, содержащим копии элементов исходного, а не ссылки.

Клон многомерного массива (например, Object [] []) является копией и это означает, что он создает только один новый массив с каждым элементом и ссылкой на исходный массив элементов, но вложенные массивы являются общими.

Средняя оценка / 5. Количество голосов:

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Или поделись статьей

Видим, что вы не нашли ответ на свой вопрос.

Ссылка на основную публикацию