Java Foundation _0306: definition and use of arrays

Source: Internet
Author: User
Tags array definition array length

Array

An array refers to a set of related variables. For example, if you want to define 100 integer variables now, it is possible to define this as a traditional idea:
int I1,i2,... i100, altogether 100 variables are written.
The above form can certainly meet the technical requirements, but here is a problem, these 100 variables do not have any logical control relationship, completely independent, will appear the object inconvenient management situation. In this case, the array can be used to solve this kind of problem.

Definition syntax for arrays
    • declare and open an array :

      数据类型 数组名称 [] = new 数据类型 [长度] ;数据类型 [] 数组名称 = new 数据类型 [长度] ;
    • * Step through * *:

      声明数组:数据类型 数组名称 [] = null ;开辟数组:数组名称 = new 数据类型 [长度] ;
      Array Operation description

      After the array has opened up space, it can be accessed in the form of "array name [subscript | index]", but all arrays are subscript starting from 0, namely: if it is an array of 3 lengths, then the subscript range: 0 ~ 2 (0, 1, 21 total three content). An array out-of-bounds exception (arrayindexoutofboundsexception) occurs when access exceeds the length of the array's allowed subscript.

The array definition structure given above uses the method of dynamic initialization, that is, the array will first open up memory space, but the contents of the array is the default value of its corresponding data type, if it is declared an array of int, then the entire contents of the array is its default value: 0.

Since the array is a sequential structure, and the length of the array is fixed, it is possible to output it in a circular way, and it is clear that the for loop is needed, and that in Java the output of the array is provided with an "array name. Length" property that can be obtained from the array length.

Defining arrays
public class ArrayDemo {    public static void main(String args[]) {        int data[] = new int[3];    // 声明并开辟了一个3个长度的数组        data[0] = 10;       // 设置数组内容        data[1] = 20;       // 设置数组内容        data[2] = 30;       // 设置数组内容        for (int x = 0; x < data.length; x++) { // 循环输出数组            System.out.print(data[x] + "、");        }    }}程序执行结果: 10、20、30、
Array manipulation

Reference passing of an array
public class ArrayDemo {    public static void main(String args[]) {        int data[] = new int[3];    // 声明并开辟了一个3个长度的数组        data[0] = 10;       // 设置数组内容        data[1] = 20;       // 设置数组内容        data[2] = 30;       // 设置数组内容        int temp[] = data;      // 数组引用传递        temp[0] = 99;       // 修改数组内容        for (int x = 0; x < data.length; x++) { // 循环输出数组            System.out.print(data[x] + "、");        }    }}程序执行结果: 99、20、30、
Array reference passing

Array static initialization
    • format one : Simplified format

      数据类型 数组名称 [] = {值,值,...} ;
    • format two : Full format

      数据类型 数组名称 [] = new 数据类型 [] {值,值,...} ;

      ```
      public class Arraydemo {
      public static void Main (String args[]) {
      int data[] = new int[] {1, 2, 3, 4, 5}; Static initialization of arrays
      for (int x = 0; x < data.length; × x + +) {//Loop output array
      System.out.print (Data[x] + ",");
      }
      }
      }
      Program execution Results: 1, 2, 3, 4, 5,

#### 二维数组 ![](http://images2017.cnblogs.com/blog/720033/201801/720033-20180124123707147-417336715.png) #### 二维数组的定义语法- **动态初始化**:

Data type array name [] = new data type [number of rows] [number of columns];

- **静态初始化**:

Data type array name [] = new data type [] {{value, value, value},{value, value, value}}

#### 观察二维数组的定义及使用

public class Arraydemo {
public static void Main (String args[]) {
int data [] = new int [] [] {
{4,5,6}, {7,8,9}
} ; Defining a two-dimensional array
for (int x = 0; x < data.length; + +) {//Outer loop is the data row content of the control array
for (int y = 0; y < data[x].length; y++) {//inner loop is the data column content of the control array
System.out.print (Data[x][y] + "\ t");
}
System.out.println (); Line break
}
}
}
Program execution Results:
1 2 3
4 5 6
7 8 9

#### 数组与方法参数的传递既然数组内容可以进行引用传递,那么就可以把数组给方法之中的参数,而如果一个方法要想接收参数,则对应的参数类型必须是数组。##### 一个数组传递的程序

public class Arraydemo {
public static void Main (String args[]) {
int data[] = new int[] {1, 2, 3}; Open array
Change (data); Reference passing, equivalent to: int temp [] = data;
for (int x = 0; x < data.length; × x + +) {
System.out.print (Data[x] + ",");
}
}
/**
* The main function of this method is to change the array data, in this method, the contents of each element in the array is multiplied by 2
* @param temp Array Reference to change the content
/
public static void Change (int temp[]) {//This method is defined in the main class and is called directly by the Main method
for (int x = 0; x < temp.length; × x + +) {
TEMP[X]
= 2; Save the contents of the array by 2
}
}
}
Program execution results: 2, 4, 6,

##### 数组与方法间的引用传递![](http://images2017.cnblogs.com/blog/720033/201801/720033-20180124123841225-981153310.png)##### 数组排序

public class Arraydemo {
public static void Main (String args[]) {
int data [] = new int [] {2,1,9,0,5,3,7,6,8};
Sort (data); Implementing sorting
print (data);
}
public static void sort (int arr[]) {//This method is specifically responsible for sorting
for (int x = 0; x < arr.length; x + +) {//Outer layer controls the number of sorting population
for (int y = 0; y < arr.length-1; y + +) {//inner control of each sort control
if (Arr[y] > arr[y + 1]) {//judgment needs to be exchanged
int t = Arr[y];
Arr[y] = arr[y + 1];
Arr[y + 1] = t;
}
}
}
}
public static void print (int temp[]) {//method that specifically defines the functionality of an output
for (int x = 0; x < temp.length; x + +) {
System.out.print (Temp[x] + ",");
}
System.out.println ();
}
}

##### 实现数组的转置(首尾交换) —— 实现思路(元素长度为偶数)![](http://images2017.cnblogs.com/blog/720033/201801/720033-20180124123911350-1546702225.png)##### 实现数组的转置(首尾交换) —— 实现思路(元素长度为奇数)![](http://images2017.cnblogs.com/blog/720033/201801/720033-20180124123933209-644460415.png)

public class Arraydemo {
public static void Main (String args[]) {
int data [] = new int [] {1,2,3,4,5,6,7};
reverse (data);//Implementing Transpose
print (data); Output array Contents
}
public static void reverse (int arr[]) {//This method specifically implements the transpose operation of an array
int len = ARR.LENGTH/2;//Number of Transpose
int head = 0; Head Index
int tail = arr.length-1; Trailing index
for (int x = 0; x < len; x + +) {//cycles to array length ÷2
int temp = Arr[head];//data exchange
Arr[head] = Arr[tail];//data exchange
Arr[tail] = temp;//data exchange
Head + +//Header index increase
Tail--;//Tail Index reduction
}
}
public static void print (int temp[]) {//array output
for (int x = 0; x < temp.length; x + +) {
System.out.print (Temp[x] + ",");
}
System.out.println ();
}
}
Program results:
7, 6, 5, 4, 3, 2, 1,

#### 数组操作方法**数组拷贝**:可以将一个数组的部分内容拷贝到另外一个数组之中;System.arraycopy(源数组名称,源数组拷贝开始索引,目标数组名称,目标数组拷贝开始索引,长度)数组排序:可以按照由小到大的顺序对基本数据类型的数组(例如:int数组、double数组都为基本类型数组)进行排序。**java.util.Arrays.sort(数组名称)**;##### 实现数组拷贝

public class Arraydemo {
public static void Main (String args[]) {
int dataa[] = new int[] {1, 2, 3, 4, 5, 6, 7, 8}; Defining arrays
int datab[] = new int[] {11, 22, 33, 44, 55, 66, 77, 88};//define an array
System.arraycopy (Dataa, 4, Datab, 2, 3); Array copy
Print (Datab);
}
public static void print (int temp[]) {//print array contents
for (int x = 0; x < temp.length; × x + +) {
System.out.print (Temp[x] + ",");
}
System.out.println ();
}
}

Program execution Results: 11, 22, 5, 6, 7, 66, 77, 88,

##### 实现排序

public class Arraydemo {
public static void Main (String args[]) {
int data[] = new int[] {3, 6, 1, 2, 8, 0};
Java.util.Arrays.sort (data); Array sorting
print (data);
}
public static void print (int temp[]) {//array output
for (int x = 0; x < temp.length; × x + +) {
System.out.print (Temp[x] + ",");
}
System.out.println ();
}
}
Program execution Results: 0, 1, 2, 3, 6, 8,

#### 对象数组数组是引用类型,而类也同样是引用类型,所以如果是对象数组的话表示一个引用类型里面嵌套其它的引用类型。在之前使用的数组都属于基本数据类型的数组,但是所有的引用数据类型也同样可以定义数组,这样的数组称为对象数组。如果要想定义对象数组(以类为例),可以采用如下的形式完成:- **对象数组的动态初始化**:

Class Name Object Array name = new class name [length];

- **对象数组的静态初始化**:

Class Name Object Array name = new class name [] {Instantiate object, instantiate object,...};

#####对象数组的动态初始化

Class Book {
Private String title;
private double price;
Public book (String t,double p) {
title = t;
Price = P;
}
Setter, getter, non-parametric structure
Public String GetInfo () {
Return "title:" + title + ", Price:" + prices;
}
}
public class Arraydemo {
public static void Main (String args[]) {
Book Books [] = new BOOK[3]; Opened a 3-length array of objects with null content
Books[0] = new book ("Java", 79.8); Each data in an array of objects needs to be instantiated separately
BOOKS[1] = new book ("JSP", 69.8); Each data in an array of objects needs to be instantiated separately
BOOKS[2] = new book ("Android", 89.8); Each data in an array of objects needs to be instantiated separately
for (int x = 0; x < books.length; x + +) {//Loop object array
System.out.println (Books[x].getinfo ());
}
}
}

Program execution Results:
Title: Java, Price: 79.8
Title: JSP, Price: 69.8
Title: Android, Price: 89.8

##### 对象数组的静态初始化

public class Arraydemo {
public static void Main (String args[]) {
Book books[] = new book[] {
New book ("Java", 79.8),
New book ("JSP", 69.8),
New book ("Android", 89.8)}; Opens up an array of three-length objects
for (int x = 0; x < books.length; × x + +) {//Loop output Object array contents
System.out.println (Books[x].getinfo ());
}
}
}
Program execution Results:
Title: Java, Price: 79.8
Title: JSP, Price: 69.8
Title: Android, Price: 89.8

```

Object Array Memory Relationship

The biggest benefit of an array of objects is the uniform management of multiple objects, and in addition to the data type changes, and the previous array is not any different, and the array itself belongs to the reference data type, then the object array is embedded in a reference data type other reference data type, If you want to represent the memory graph, you can simply understand the structure shown in the diagram.

Java Foundation _0306: definition and use of arrays

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.