JAVA basics-array explanation, java array explanation

Source: Internet
Author: User

JAVA basics-array explanation, java array explanation
Learning how to use arrays in JAVA 1. What is an array?

Q: write the code to save the scores of the four students.

A: It's easy. Define four variables.

Q: Is it swollen to calculate the scores of 400 students in all grades?

A :.......

  ArrayTo help you solve the problem !!

Array can be understood as a huge "box", which canIn orderStore multipleSame typeFor example, the int-type array scores can be defined to store the scores of four students.

    

All elements in the array can be accessed by subscript. The subscript starts from 0. For example, you can use scores [0] to obtain the first element 76 in the array. scores [2] can get the third element 92!

Ps: the value in the array name (without subscript) for this arrayStorage address. (We will learn more about this role in the future)

2. Use the array in java (1) Declaration and simple operations Array

  Because java is an object-oriented language, no matter which operation you want to use must be performed with an object, arrays are no exception, to use an array, you must first declare the array object and then allocate space to it (generate an object with instances) for normal use.

To operate arrays in Java, you only needFour steps:

1. Declare an array

Syntax:Data Type [] array name;

OrData Type array name [];

The array name can be any valid variable name, for example:

  

2. Allocate space

Simply put, it is to specify the maximum number of elements that can be stored in an array.

Syntax:Array name = new data type [array length];

The length of the array is the number of elements that can be stored in the array, for example:

  

Ps: in our daily use process, we usually combine the above two steps to allocate space for the array while declaring it, such:

  

  3. Assignment

After allocating space, you can put data into the array,All elements in the array are accessed by subscript.For example, to store student scores in the scores array:

  

  4. process data in the array

We canAfter assignmentOperations and processing, such as obtaining and outputting the values of elements in the array:

  

Note:

In Java, another method is provided for directly creating arrays.Declare an array, allocate space, and assign values (Steps 1, 2, and 3 above)Merge completed, for example:

  (The length of the array is determined by the number of values assigned.)

It is equivalent:

  (Note: The array length must be blank !!)

(2) operate arrays in Java using Loops

In actual development, we often use loops to control the operations of array members. For example:

  

Running result:

  

Where,Array name. lengthUsed to obtain the length of an array

Notes ":

1,Array subscript starts from 0. Therefore, scores [3] indicates 4th elements in the array, instead of 3rd elements.

2. ArrayThe following value ranges from 0 to array length-1., IfOut of boundsAn error is reported. For example:

  

The error message above indicates that the array subscript exceeds the range, that is, the array access is out of bounds. In the above Code, create an array with a length of 2, so the range of the array subscript is 0 to 1, and the subscript in the program appears 2, that is, scores [2], beyond the range, the array access is out of bounds.

(3) Use the Arrays class to operate Arrays in Java

The Arrays class isToolIn the java. util package. This class contains some methods usedDirectly operate on ArraysFor example, you can directly sort and search arrays.

Common Methods in Arrays:

  1. Sorting

Syntax:Arrays. sort (array name );

You can use the sort () method to sort the array. You only need to put the array name in the brackets of the sort () method to sort the array.(In ascending order)Such:

  

Running result:

  

Note: Arrays. sort (hobbys); If the element in hobbys isString, ThenCompare the alphabetic order !!!That is, the first letter of an element is placed in the front, and the first letter is equal to the first letter.

Arrays. sort ()Numbers are ascending and letters are sequential.

  2. convert an array to a string

Syntax:Arrays. toString (array name );

You can use the toString () method.Converts an array to a string.In this method, multiple array elements are connected in order.Comma and SpaceSeparated, such:

    

The running result is:Elements in the output array nums: [,]

Ps: The toString () function is an output string (converted to a string) function that comes with java. Many built-in classes have this function, we can rewrite it to implement a custom output string style. The default output style is separated by [] and use, just like in the example.

The Arrays class also provides many other methods to operate Arrays. Here we will not list them one by one. You can view the results of other bloggers in my next article)

Connection: http://www.cnblogs.com/hysum/p/7094232.html

(4) using foreach to operate Arrays

Foreach is not a keyword in Java, but a for statement.Special simplified versionWhen traversing arrays and sets, foreachSimpler and more convenient. To understand the meaning of foreach, that is, "for each", how can we use foreach statements?

Syntax:

  

We use the for and foreach statements to traverse the array respectively, and use the example to see if foreach is simpler and more convenient.

Public static void main (String [] args) {// TODO Auto-generated method stub \ String [] test = {"this is", "one", "test Case "}; system. out. println ("using for loop output array"); for (int I = 0; I <test. length; I ++) {System. out. print (test [I]);} System. out. println (); System. out. println ("using foreach loop output array"); for (String t: test) {System. out. print (t );}}

Running result:

  

  

It's convenient to see foreach !!

Leave a question to everyone: What should I do if I want to obtain the subscript of the array element in the foreach statement ??

The answer is simple. Just set a subscript variable, as shown below:

Int I = 0; for (type variable: array) {I ++; // auto-increment 1 for each loop. Remember to subtract 1 for the output because the lower label is required}
3. Two-dimensional array in Java

The so-called two-dimensional array can be simply understood as a "special" one-dimensional array, which stores a one-dimensional array in each array space.

To use a two-dimensional array, follow these steps:

  1. Declare an array and allocate space

  

Or

  

For example:

   

2. Assignment

The assignment of two-dimensional arrays is similar to that of one-dimensional arrays. You can assign values one by one using subscript. Note that the index starts from 0.

  

You can also assign values to an array while declaring it.

  

For example:

  

  3. Process Arrays

The access to a two-dimensional array is the same as the output of an array of the same dimension, but there is an additional subscript. When loop output is requiredInsert a loop, That is, useDual LoopTo output every element in a two-dimensional array. For example:

Public static void main (String [] args) {// TODO Auto-generated method stub \ // define a two-dimensional array with two rows and three columns and assign values to int [] [] num = {, 3, 6 }}; // locate the row for (int I = 0; I <num. length; I ++) {// locate the element of each row for (int j = 0; j <num [I]. length; j ++) {// output each element in sequence (without line feed) System. out. print (num [I] [j]);} // implement line feed (each line is output) System. out. println ();}}

Running result:

  

  You need to know:You can also define a two-dimensional array.Specify the number of rowsAnd then specify the number of columns for each row. IfThe number of columns in each row is different., The created isIrregular two-dimensional array, As shown below:

The running result is:

          

Note the following before using a two-dimensional array:

  • The length of the two-dimensional array isNumber of rows, Not the number of all elements;
  • The rows of a two-dimensional array can be seen asOne-dimensional arrayThat is, two-dimensional arrays are actually composed of multiple (column) one-dimensional arrays;
  • You can use the array name [row number]. length to obtainNumber of Columns;

 

Note: This article is based on my summary of MOOC's online java courses. Interested partners can go to MOOC for video learning and online programming, understanding knowledge points faster and better ~ You are welcome to refer to the knowledge point PHI (> ω <*) at any time *)

  

  

 

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.