Java arrays

Source: Internet
Author: User

Tags: after introduction program mode first image Basic tab PIL

Arrays are one of the most important data structures in any programming language, and different languages are implemented and processed differently. Anyone who has written a program knows the value of the array and the importance of understanding the array, along with the linked list, consisting of the numbers for the basic data structure. Although Java provides a great collection API and collection classes such as: ArrayList, HashMap, they are all based on arrays. If you're from a C-or C + + background programmer, you'll find some similarities and differences in how arrays behave and how they work in Java. The most notable is the bounds checking of arrays in C and Arrays in Java, the C compiler does not check if the program accesses an invalid array index, and Java throws arrayindexoutofboundexception if the program tries to access an invalid array index. In this article, we look at arrays in Java, including arrays of primitive types and object types, and here are some points of knowledge about Java arrays and properties.

Java Array 101

(101 refers to the introduction of a thing, the reader does not need any preparatory knowledge)

1) An array is an object in Java, and an array instance is created using the new operator. ARRAY.LENGTH Specifies the length of the array, for example:

1234 int[] intArray = newint[10];System.out.println(intArray.length)Output: 10

Array.Length represents the capacity of the array, as long as the array is created, and each index is initialized to the default value.

2) array index Start is 0, negative index in Java is invalid, will throw arrayindexoutofboundexception, if you try to access an array with an invalid index, this invalid index may be a negative index, or is greater than or equal to the length of the array index.

3) The array is stored in a contiguous memory space in the Java heap, so if you create a large index, you can have enough heap space until the OutOfMemoryError is thrown because the requested memory size is not available in contiguous memory space.

4) array a fixed-length data structure, once declared, you cannot change the length of the array.

5) Different types of arrays have different types, such as the following example, Intarray.getclass () differs from Floatarray.getclass ()

12 int[] intArray = newint[10];float[] floatArray = newfloat[10];
1 6 ) you cannot store double int
12 int[] intArray = newint[10];intArray[5]=1.2; //compilation error

If you try to do this at run time, Java throws Arraystoreexception

7) In a Java array can be created in different ways, here is an example of creating an array:

1234 int[] intArray;   //creating array without initializing or specifying sizeint intArray1[];  //another int[] reference variable can hold reference of an integer arrayint[] intArray2 = new int[10]; //creating array by specifying sizeint[] intArray3 = new int[]{1,2,3,4}; //creating and initializing array in same line.

You can either initialize the array at the time you create the array, or you can initialize it later with a for loop, and the brackets can be preceded by the variable or after the variable.

The first method is convenient to create multiple arrays such as:

Int[] Array1, array2

The array1 and array2 here are integral arrays, and the second method you need to put two parentheses, such as:

int array1[], array2[]

Although there are not many differences in style, I read "int[" called int array, which is easier to understand.

8) If an array element is not explicitly initialized, the array is initialized with the default type value, for example, if an integer array is not initialized, the element will default to 0, the Boolean value without initialization is false, and the object array is null.

9) You can access the array element by using the [] operator, because the array index starts at 0,[0] returns the first element, [length-1] returns the last element, and the For loop is a convenient way to iterate over the entire array. You can use a for loop to initialize the entire array, access each index or update, and get the array elements. JAVA5 also provides a reinforced for loop, an array to manage the index itself, to prevent arrayindexoutofboundexception, here is an example of an iteration:

The traditional way:

123456789101112 int[] numbers = new int[]{10, 20, 30, 40, 50};for (int i = 0; i < numbers.length; i++) {  System.out.println("element at index " + i + ": " + numbers[i]);}Output:element at index 0: 10element at index 1: 20element at index 2: 30element at index 3: 40element at index 4: 50

Enhanced for Loop

12345678910 for(inti: numbers){   System.out.println(i);}Output:1020304050

As you can see, the enhanced for loop does not need to check the array index, which is a good method if you want to access all the elements individually, but also because you cannot access the index, you cannot modify the array elements.

The array in Java can be easily converted into ArrayList. ArrayList an index-based collection, which is an alternative to arrays. The advantage of ArrayList is that you can change the size of a volume by simply creating a larger array and then copying the contents to the new array, but you cannot change the size of the array.

Java API also provides some handy ways to manipulate arrays through the Java.utils.Arrays class, by using arrays you can sort the array, you can do a binary search.

The Java.lang.System class provides a practical way to copy elements to another array. System.arraycopy is very powerful and flexible when copying content from one array to another. You can copy the entire or sub-array, depending on your needs.

System.arraycoy Syntax:

1 publicstatic void arraycopy(Object src, int srcPos, Object dest, int destPos, intlength)

As you can see, Arraycopy allows us to specify the index and length, which gives you the flexibility to copy the Subarray and store it to the desired location or destination array. Here is an example of copying the first three elements to the target array:

1234567891011121314151617181920212223242526272829 public static void main(String args[]) {        int[] source = new int[]{10, 20, 30, 40, 50};        int[] target = new int[5];        System.out.println("Before copying");        for(int i: target){            System.out.println(i);        }        System.arraycopy(source, 0, target, 0, 3);        System.out.println("after copying");        for(int i: target){            System.out.println(i);        }    }Output:Before copying00000after copying10203000

You can see that all the elements before the copy are 0, and then the first three elements are replaced.

Java also supports multidimensional arrays, which are useful when representing 2D and 3D, like rows and columns or matrices. A multidimensional array is also an array of arrays, and here is an example of creating a multidimensional array:

1 int[][] multiArray = newint[2][3];

This is an array with 2 rows and 3 columns, or an array of length 2, in which each element holds an array of length 3, which is an example of initializing a multidimensional array:

123 int [][] MultiArray = {{ 1 2 Code class= "Java value" >3 },{ 10 20 30 system.out.println (multiarray[ 0 ].length); system.out.println (multiarray[ 1 ].length);

14) An array is a very fast data structure, and if you already know the length of the element, you should use an array rather than a data structure such as ArrayList.

The above is all about the array, as you can see, the array is a very powerful data structure.

Original link: javarevisited translation: Zhijun
[ Reprint please keep the source, translator and translation links.] ]

Java arrays

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: