I Genius official Free tutorial 26: An array of Java basic teaching routines

Source: Internet
Author: User
Tags array length

Array

Example: If there are now 10 people lined up as a team "Zhang San, John Doe, Harry ...", the team called a, and then asked the first person from 0 to count off "Zhang three newspaper 0, John Doe 1, Harry 2 ...". Now ask the first person to dequeue, but now do not know Zhang San's name, how to do? Then you can only ask team a No. 0. May I ask who will be out now? It was obviously Zhang San.
This creates an array-like structure where team name a corresponds to the array name, each individual's number corresponds to the subscript of the array, and each person corresponds to the element in the array, and the number of people corresponds to the length of the array.
In the program design, a number of variables of the same type are grouped together in an orderly form, using only one variable name to store the elements, with subscript (subscript starting from 0) to correspond to different positions of variables, this is the array.


Create an array

Declaration Syntax Format:
Way One,data type [] Variable name = {Data 1, data 2, .... Data n};
Way Two,data type [] Variable name = new data type []{data 1, Data 2, .... Data n};
Way Three,data type [] Variable name = new data type [length value];
Assignment Syntax Format:
variable name [subscript] = value;


Instance:
/*
After executing this code, there is a variable called I in Memory, and occupies 3 consecutive space of type int (that is, 12 bytes of memory space), and the length of each int type (4 bytes) is numbered from left to right, numbering starts at 0. The value 1 of the int type is then deposited into 4 bytes numbered 0, 2 is deposited in 1 bytes numbered 4, and 3 is deposited in 2 bytes numbered 4. and copy the starting address of this 12-byte memory space to the variable i
where int is the data type, [] The brackets represent the array, the variable name I is also known as the array name, and the {} curly braces represent the array constants (which contain array elements), where the data is three (3) elements of the array (separated by commas in English format between multiple elements), corresponding numbers 0, 1, 2 is the subscript of the array.
*/
Int[] I = {1, 2, 3};
Creates an array of type string of length 5;
The new action here is to create the array object, so it follows the brackets and the length: type [length]
string[] str = new STRING[5];
Assigns an element to an array, where 0 in str [0] represents the subscript
str [0] = "abc";
The new operation here is to create a string object, so it is followed by parentheses instead of brackets;
The created string object is then assigned to the position labeled 1 in the array
str [1] = new String ("XYZ");
The error occurs because the length of the array is 5 and the subscript is 0 to 4
This uses 5 as subscript, beyond the bounds of the array subscript
STR[5] = "AAA"


Attention:
A method can only be written in one statement and cannot be split into two statements;
For example: int i;  i = {1, 2, 3}; This is wrong.
Mode two new type []{}; The length value cannot be written in brackets [], and the number of elements in the curly braces is the length value
Mode three new type [3]; The length value must be written in brackets []
In addition: When declaring an array variable [] can be written in the data type, it can also be written after the variable name, such as: int i[];


An array is a reference type whose reference can point to any array object of the same type, but once the array object is created, its length cannot be changed. And the memory space occupied by the array object must be contiguous.


manipulating Arrays

Use subscript to access data in an array
Syntax format: array name [subscript]
Gets the length of the array: array name. length;

The instance:package array;/** *  operation Array class operationarray *  implements adding data to the array  *  accessing the data in the array  *   Querying data in an array  *  modifying data in an array  *  inserting data into an array  *  deleting data in an array  *  @author   Genius Alliance  -  Yukun  */public class operationarray {public static void main ( String[] args)  {//creates a string array of length 4 to store student names string[] studentnames = new string[4];// Adds a value to the array, the last position in the array has no value added, the reference type default value is nullstudentnames[0] =  "Zhang San";studentnames[1] =  "John Doe"; studentnames[2] =  "Harry"; System.out.println ("-----------  values in the initial array  -----------");//Call the method Ergodicarray (Studentnames) to iterate over the array; System.out.println ("-----------  query data  -----------");//Query the position of "John Doe" in the array for  (int i = 0 ;  i < studentnames.length; i++)  {//determine whether the contents of two strings are identical using the Equals method, and cannot use the double equals ==//with the string "John Doe" In sequence and in the string comparison in the array, if the same Equals method returns trueif  ("John Doe". Equals (Studentnames[i]))  {system.out.println (" John Doe in the array studentnamesThe subscript is: "+i);//If" John Doe "is found, no further searching is required, ending the loop with break;} Else if (i == studentnames.length - 1) {//determines if I is equal to the last subscript of the array//or "John Doe" is not found) This block of code is executed multiple times System.out.println ("Li IV is not found in array Studentnames");}} System.out.println ("-----------  modified data  -----------");//change subscript 2 to "Harry" to "Zhao Liu" studentnames[2] =  "Zhao Liu";//Call the method of traversing the array, output the modified data Ergodicarray (studentnames); System.out.println ("-----------  inserted data  -----------");/* *  the position labeled 2 to reinsert the Harry  *  Since it is an insert, each element from subscript 2 to the end of the array moves backwards one  *  then assigns the position subscript 2 to "Harry"  *  so the For loop is accessed from the first element in the array, That is, the studentnames.length-1 *  is equal to 2 o'clock and the subscript is a continuously decreasing  */for  (int i =  studentnames.length - 1; i >= 2; i--)  {//assigns the value of the previous position to a later position, This implements the position of each element move studentnames[i] = studentnames[i-1];if  ( i == 2 )  {/*  *  the current Mark equals 2 o'clock, move the original value to 3,  *  then assign the new value to be inserted at the position labeled 2  *  so the code that assigns the new value should be behind the displacement Code  */ studentnames[2] = "Harry";}} Call the method of traversing the array, output the modified data Ergodicarray (studentnames); System.out.println ("-----------  deleted data  -----------");/* *  Delete the value at the location labeled 2, deleting the "Harry" that you just inserted   *  after deletion should go back to insert "Harry" before the state  *  exactly and insert the opposite, delete is the 2-bit after each position of the element moved forward one  */for  (int i =  2; i < studentnames.length; i++)  {if  ( i ==  studentnames.length - 1 )  {/* *  When the current label is equal to the last position of the array, there are no more values behind it  *  So there is no need to perform a move operation, where the last position value is assigned to Null */studentnames[i] = null;} else{//the value on the next position, assigns the value to the previous position, thereby moving the element's position to move studentnames[i] = studentnames[i+1];}} Call the method that iterates through the array, outputting the modified data Ergodicarray (studentnames);} /** *  the method of traversing an array; traversal: is a single access  *  where parameters are required to traverse the array  *  because many need to traverse the output array value, so put it into a method  *   This method can be reused to iterate through the output code in a location that needs to be used  */private static void ergodicarray (string[]  Array)  {//each value in the loop output array for  (int i = 0; i < array.length; i++) & nbsp; {//Use subscript to access values in the Array and tab System.out.print (array[i] +  "\ t");} Output line break System.out.print ("\ n");}} Run Result:-----------  values in the initial array  -----------Dick and Harry Harry null-----------  query data  ----------- John Doe the subscript in the array studentnames is: 1-----------  modified data  -----------Zhang Sanli null-----------  inserted data  ------ -----Dick and Harry Harry Zhao Liu-----------  deleted data  -----------Zhang Sanli null


two-dimensional arrays

Is that each element in a one-dimensional array is also a one-dimensional array, so that the array is a two-dimensional array.
Method One, data type [] Array name = {{value 1,... Value n},{value 1,... Value m},{value 1,... Value k}};
Mode two, data type [] [] array name;
Array name = new data type [][]{{....},{...}};
Like a one-dimensional array, the way one can only be written in a single statement, can not be divided into two statements written;

Method Three, data type [] Array name = new data type [outer array length] [inner array length];
Array name [0][0] = value;
Mode four, data type [] Array name = new data type [outer array length] [];
Array name [subscript] = new data type [length];

traversing a two-dimensional array

Example: Package array;/** * twodimensionalarraydemo class: Demo Two-dimensional array  *  @author   Genius Alliance  -   Yukun  */public class twodimensionalarraydemo {public static void main ( String[] args)  {/* *  declares a two-dimensional array of type string classroom *  the length of the first dimension is 2 and the length of the second dimension is 3 *  A one-dimensional array of length 2, each of which is a one-dimensional array of length 3  */string[][] classroom = new string[2][3];classroom[0] [0] =  "1th row 1th column";classroom[0][1] =  "1th row 2nd Column";classroom[0][2] =  "1th row 3rd column"; classroom[1 ][0] =  "2nd row 1th column";classroom[1][1] =  "2nd row 2nd Column";classroom[1][2] =  "2nd row 3rd Column";// Loop gets each element in the first-dimensional array for  (int i = 0; i < classroom.length; i++)  {// Each of these elements is also a one-dimensional array string[] row = classroom[i];/* *  The one-dimensional array that is retrieved once again  *  where row.length   equivalent to  classroom[i].length */for  (int j = 0; j < row.length ;  j++)  {/* *  gets a string value at this point  *  where row[j]  is equivalent to  classroom[i][j] */system.out.println (Row[j]);}}} Run Result: 1th row 1th column 1th row 2nd column 1th row 3rd column 2nd row 1th column 2nd row 2nd column 2nd row 3rd column


This article from the "Genius Union Education Official Blog" blog, reproduced please contact the author!

I Genius official Free tutorial 26: An array of Java basic teaching routines

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: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.