Java filling an array

Copying and Filling Arrays in Java

Besides sorting and searching, the java.util.Arrays class provides also convenient methods for copying and filling arrays. In this article, we’re going to help you understand these functionalities in details with full code examples.

1. Copying Arrays Example

The Arrays class provides convenient methods that return a new array which is a copy of a specified array. The newly returned array can have same, less or more elements than the original array. If have more, the new array is padded with default values for the extra elements. Below is the list of such methods ( X denotes a primitive type; U and X denote reference types):

  • X[] copyOf(X[] original, int newLength)
  • T[] copyOf(T[] original, int newLength)
  • T[] copyOf(U[] original, int newLength, Class newType)
  • X[] copyOfRange(X[] original, int from, int to)
  • T[] copyOfRange(T[] original, int from, int to)
  • T[] copyOfRange(U[] original, int from, int to, Class newType)

The following example illustrates how to copy primitive arrays:

int[] original = ; int[] copy1 = Arrays.copyOf(original, original.length); int[] copy2 = Arrays.copyOf(original, 5); int[] copy3 = Arrays.copyOf(original, 15); System.out.println("original array: " + Arrays.toString(original)); System.out.println("copy #1 (same length): " + Arrays.toString(copy1)); System.out.println("copy #2 (truncted): " + Arrays.toString(copy2)); System.out.println("copy #3 (padded): " + Arrays.toString(copy3));
original array: [199, 299, 399, 499, 599, 699, 799, 899, 999] copy #1 (same length): [199, 299, 399, 499, 599, 699, 799, 899, 999] copy #2 (truncated): [199, 299, 399, 499, 599] copy #3 (padded): [199, 299, 399, 499, 599, 699, 799, 899, 999, 0, 0, 0, 0, 0, 0]

Similarly, the following code snippet shows how to copy an array of String objects:

String[] original = ; String[] copy1 = Arrays.copyOf(original, original.length); String[] copy2 = Arrays.copyOf(original, 3); String[] copy3 = Arrays.copyOf(original, 10); System.out.println("original array: " + Arrays.toString(original)); System.out.println("copy #1 (same length): " + Arrays.toString(copy1)); System.out.println("copy #2 (truncated): " + Arrays.toString(copy2)); System.out.println("copy #3 (padded): " + Arrays.toString(copy3));
original array: [Apple, Banana, Carrot, Lemon, Orange, Grape] copy #1 (same length): [Apple, Banana, Carrot, Lemon, Orange, Grape] copy #2 (truncated): [Apple, Banana, Carrot] copy #3 (padded): [Apple, Banana, Carrot, Lemon, Orange, Grape, null, null, null, null]

The following example shows how to copy an array of Integer to an array of Number ( Number is the super type of Integer ):

Integer[] integers = ; Number[] numbers = Arrays.copyOf(integers, integers.length, Number[].class); System.out.println("Numbers: " + Arrays.toString(numbers));
Numbers: [16, 32, 64, 128, 256, 512]
int[] original = ; int[] copy = Arrays.copyOfRange(original, 3, 8); System.out.println("Original: " + Arrays.toString(original)); System.out.println("Sub copy: " + Arrays.toString(copy));
Original: [8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096] Sub copy: [64, 128, 256, 512, 1024]

2. Filling Arrays Example

Sometimes you need to assign the same value for all elements of an array (or “reset” the entire array with a value). The Arrays class provides such methods ( X denotes a primitive type):

  • void fill(X[] a, X val)
  • void fill(X[] a, int fromIndex, int toIndex, X val)
  • void fill(Object[] a, Object val)
  • void fill(Object[] a, int fromIndex, int toIndex, Object val)
Читайте также:  Как питон душит свою жертву

The following code fills zeroes to an array of integers:

int[] numbers = ; System.out.println("Before fill: " + Arrays.toString(numbers)); Arrays.fill(numbers, 0); System.out.println("After fill: " + Arrays.toString(numbers));
Before fill: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21] After fill: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

The following code “resets” Strings in an array to null:

String[] fruits = ; System.out.println("Before fill: " + Arrays.toString(fruits)); Arrays.fill(fruits, null); System.out.println("After fill: " + Arrays.toString(fruits));
Before fill: [Banana, Apple, Orange, Lemon, Mango] After fill: [null, null, null, null, null]

And the following code snippet fills only a half of an array:

double[] doubles = ; System.out.println("Before fill: " + Arrays.toString(doubles)); Arrays.fill(doubles, 0, doubles.length / 2, 0.0); System.out.println("After fill: " + Arrays.toString(doubles));
Before fill: [1.23, 2.34, 3.45, 4.56, 5.67, 6.78, 7.89, 8.9] After fill: [0.0, 0.0, 0.0, 0.0, 5.67, 6.78, 7.89, 8.9]

3. Array to String

As you can see in the examples throughout this article, the Arrays class provides convenient methods for representing elements of an array in String format ( X denotes a primitive type):

String deepToString(Object[] a)

Here’s an example that prints content of a 2-dimenson array:

String[][] persons = < , , >; System.out.println(Arrays.deepToString(persons));
[[Tom, USA, Developer, Jogging], [John, Canada, Designer, Painting], [Alice, UK, Tester, Biking]]

References:

Other Java Collections Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Заполнить массив в Java

Заполнить массив в Java

  1. Используйте < >для заполнения массива в Java
  2. Использование цикла for для заполнения массива в Java
  3. Используйте метод Arrays.copyOf() для заполнения элемента в массиве Java
  4. Используйте метод Arrays.fill() для заполнения элементов в массиве Java
Читайте также:  Compile java source to class

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

В массиве примитивных типов данных элементы хранятся в непрерывной области памяти. Напротив, в непримитивном типе данных элементы хранятся в динамической памяти (сегмент кучи).

В этом руководстве мы заполняем массив на Java. Заполнить здесь означает заполнить массив некоторыми значениями.

Используйте < >для заполнения массива в Java

Это основной и один из простейших методов заполнения массива. Фигурные скобки <> используются для определения элементов массива.

import java.util.*; public class Num  public static void main(String args[])    int arr[] =  1, 3, 5, 7, 11 >; // Declaration of elements using   for (int j = 0; j  arr.length; j++)    System.out.print(array[j] + " ");  >  > > 

Использование цикла for для заполнения массива в Java

Класс Scanner используется для сканирования элементов массива от пользователя. Запускаем цикл до тех пор, пока на каждой итерации не будет введена длина пользователя и использование объекта элементов класса Scanner .

import java.util.Scanner; public class ArrayInputUsingLoop  public static void main(String[] args)  int number; Scanner obj=new Scanner(System.in); System.out.print("Total number of elements: "); number=obj.nextInt(); int[] array = new int[20]; System.out.println("Enter the elements of the array: "); for(int i=0; inumber; i++)  array[i]=obj.nextInt(); //reads elements from the user  > System.out.println("Array elements you entered are: "); for (int i=0; inumber; i++)  System.out.println(array[i]); > > > 
Total number of elements: 5 Enter the elements of the array: 5 4 3 2 1 Array elements you entered are: 5 4 3 2 1 

Используйте метод Arrays.copyOf() для заполнения элемента в массиве Java

Метод Array.copyOf() относится к классу java.util.Arrays . Эта функция копирует конкретный массив и усекает его нулями или нулевыми значениями, если необходимо, чтобы сохранить заданную длину копируемого массива.

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

import java.util.Arrays;  public class Main   public static void main(String[] args)    int[] array1 = new int[] 8,9,10,11,12>;   System.out.println("First array is:");  for (int i = 0; i  array1.length; i++)   System.out.println(array1[i]);  >   int[] array2 = Arrays.copyOf(array1, 7);  array2[5] = 6;  array2[6] = 7;   System.out.println("New array after copying elements is:");  for (int i = 0; i  array2.length; i++)   System.out.println(array2[i]);  >  > > 
First array is: 8 9 10 11 12 New array after copying elements is: 8 9 10 11 12 6 7 

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

import java.util.Arrays;  public class ArrayCopy  public static void main(String args[])     int[] originalarray = new int[] 7, 8, 9>; System.out.println("The Original Array is : \n"); for (int i = 0; i  originalarray.length; i++)  System.out.print(originalarray[i] + " ");  int[] copyarray = Arrays.copyOf(originalarray, 5);  System.out.print("\nNew Array copy of greater length is:\n"); for (int i = 0; i  copyarray.length; i++)  System.out.print(copyarray[i] + " "); > > 
The Original Array is : 7 8 9 New Array copy of greater length is: 7 8 9 0 0 

Используйте метод Arrays.fill() для заполнения элементов в массиве Java

Метод Arrays.fill() относится к классу java.util.Arrays .

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

import java.util.Arrays;  public class ArrayFill   public static void main(String[] args)    int array[] = 6, 7, 8, 9, 10>;   Arrays.fill(array, 5);  System.out.println(Arrays.toString(array)); > > 

Исходный массив можно частично заполнить новыми элементами, указав индекс.

import java.util.Arrays;  public class ArrayFill2   public static void main(String[] args)    int array[] = 7, 8, 9, 10, 11>;   Arrays.fill(array, 2, 5, 0); // Replace elements from index 2 to index 4 by 0   System.out.println(Arrays.toString(array)); > > 

Сопутствующая статья — Java Array

Источник

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