Массивы,
Массивы
- Массивы представляют собой набор элементов данных одного и того же типа с непрерывным расположением памяти.
- Массивы в Java основаны на индексах, например, первый элемент хранится в индексе 0, а второй элемент хранится в индексе 1.
Преимущества
- Оптимизация кода: это оптимизирует код, мы можем эффективно извлекать или сортировать данные.
- Произвольный доступ: мы можем получить любые данные, расположенные в позиции индекса.
Недостатки
- Ограничение по размеру: мы можем хранить только элементы фиксированного размера в массиве. Он не увеличивается в размерах во время выполнения. Для решения этой проблемы в Java используется структура коллекций, которая растет автоматически.
Синтаксис объявления массива в Java
- тип данных[] обр; (или)
- тип данных []обр; (или)
- тип данных обр[];
Создание экземпляра массива в Java
arrayRefVar=новый тип данных[размер];
Пример массива 1(for)
public class ArrayExample { public static void main(String[] args){ // int []studentMarks; // int studentMarks[]; int[] studentMarks; studentMarks = new int [10]; studentMarks [0] = 23; studentMarks [1] = 56; studentMarks [2] = 87; studentMarks [3] = 98; studentMarks [4] = 85; studentMarks [5] = 25; studentMarks [6] = 87; studentMarks [7] = 23; studentMarks [8] = 45; studentMarks [9] = 37; // studentMarks [10] = 98; This line will be a error because of the size of the array is only 10 for (int index=0; index < studentMarks.length; index++){ System.out.println("The value in the index "+ index + " is " + studentMarks[index]); } } } -------------------------------------------------------------------- The value in the index 0 is 23 The value in the index 1 is 56 The value in the index 2 is 87 The value in the index 3 is 98 The value in the index 4 is 85 The value in the index 5 is 25 The value in the index 6 is 87 The value in the index 7 is 23 The value in the index 8 is 45 The value in the index 9 is 37 Process finished with exit code 0
Пример массива 2(для каждого)
public class ArrayExample { public static void main(String[] args){ int[] studentMarks; studentMarks = new int [10]; studentMarks [0] = 23; studentMarks [1] = 56; studentMarks [2] = 87; studentMarks [3] = 98; studentMarks [4] = 85; studentMarks [5] = 25; studentMarks [6] = 87; studentMarks [7] = 23; studentMarks [8] = 45; studentMarks [9] = 37; for (int mark : studentMarks) { System.out.println(mark); } } } -------------------------------------------------------------------- 23 56 87 98 85 25 87 23 45 37 Process finished with exit code 0
- Следующий код упростит приведенный выше пример 2 (для каждого)
public class ArrayExample2 { public static void main(String[] args){ int[] studentMarks = {23, 56, 87, 98, 85, 25, 87, 23, 45, 37}; for (int mark : studentMarks) { System.out.println( "The marks of the student :" + mark); } } } -------------------------------------------------------------------- The marks of the student :23 The marks of the student :56 The marks of the student :87 The marks of the student :98 The marks of the student :85 The marks of the student :25 The marks of the student :87 The marks of the student :23 The marks of the student :45 The marks of the student :37 Process finished with exit code 0