Explanation of reference examples of java array elements

  • 2021-09-04 23:58:28
  • OfStack

For arrays, we want to refer to one of the elements, which can not be separated from the use of new. When you learn new, 1 generally appears as new and initialized. If it is used on an array reference, it will appear as an operator. Let's take a look at the array elements that are referenced in the new operator.

You can only reference each element in an array by defining and allocating space with the operator new:

(1) arrayName [index]

index is an array element subscript, which can make the shaping always bright or shape the expression. Such as:


a[3], b[i], c[6*i];

(2) The subscript of array elements starts from 0; The legal subscript range for an array of length n is:

0~n-1;

Extension: Each array has an attribute lendth (note: length is an attribute, not a method, without parentheses (), which we specifically explain here to distinguish it from String's length () method), indicating its length, for example:

The value of a. length is the length (number of elements) of the array a

Note:


public static void main(String args[]){}

The main function in each of our classes also has an array called srgs, so why do you use this array? This array is like, we inject all in ipconfig-all on the command line. We can enter java TestArray (class name) 23, 12, aa, bbb and several parameters. It can then be output in the code to see.

Instance extension:

(1) fill (int [] a, int value)

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

a: Array for element substitution; value: To store the values of all elements in the array.

Example 1: Create a class Swap in the project, create a 1-dimensional array in the main method, fill the array elements through the fill () method, and finally output each element in the array.


import java.util.Arrays;
public class Swap {
	public static void main(String[] args) {
		int arr[] = new int[50];
		Arrays.fill(arr,99);
		for(int i = 0;i<arr.length;i++) {
				System.out.println(" No. 1 " + i+ " The elements are: " + arr[i]);
		}
	}
}

(2) fill (int [] a, int frimIndex, int toIndex, int value)

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

The example code is as follows:


import java.util.Arrays;

public class Displace {
	public static void main(String[] args) {
		int arr[] = new int[] {99,88,77,66,55,44,33,22,11};
		Arrays.fill(arr,1,3,1000);
		Arrays.fill(arr,5,6,1000);
		for(int i = 0;i<arr.length;i++) {
			System.out.println(" No. 1 "+i+" The elements are: "+ arr[i]);
		}
	} 
}

fill () can be used many times to replace different elements in the array, which you can try 1. Everyone 1 must knock the code with their own hands, don't copy and paste it, which is very helpful to study and work in the future!


Related articles: