Getting Started with Java Tutorial seven (array)

Is the most common form of array data structure, it is the same type of identifier with a data type of package to the base sequence of the target sequence or together. Array using a single array name and a different index to uniquely identify elements in the array. Essentially, the array is a simple linear sequence, and therefore fast access

One-dimensional array

Linear same group set a type of data, once declared size of the array can not be modified.

create

Data Type [] array name; Data type can be either basic data types, data types may be referenced

String[] name; 
Person[] persons;

Allocated space

Allocate space is to tell the computer is assigned several consecutive location to store data in memory for it. You can use the new keyword to allocate space for the array in Java

name =new String[10];
persons =new Person[30];

Create and assign space

int arr=new int[5];

One-dimensional array initialization

Arrays can perform an initialization operation, initialization of the array at the same time, can specify the size of the array, each element may also initializes the array

int[] number=new int[5];
number[0]=1;
number[1]=2;
number[2]=3;
number[3]=5;
number[4]=8;
//或
int[] number=new int[]{1, 2, 3, 4, 5};
//或
int[] number={1,2,3,5,8};

Gets the element

The array index where the specified elements get

int[] number={1,2,3,4,5};
System.out.println(number[0]);//输出1

Traversal

Use a for loop to traverse the entire number of elements in the array

int[] number={1,2,3,4,5};
for (int i=0;i<number.length;i++)
{
    System.out.println(number[i]);//依次输出1,2,3,4,5
}

Two-dimensional array

In the first subscript represents the element at which the row, the second subscript represents the column element is located, is seen as a two-dimensional array array of arrays

create

type indicates the type of two-dimensional arrays, array represents an array name, in parentheses represent the first row, the second row in parentheses

type[][] array;//例:int[][] age;

initialization

array=new type[][]{值 1,值 2,值 3,…,值 n};
array=new type[][]{new 构造方法(参数列),…};
type[][] array={{第1行第1列的值,第1行第2列的值,…},{第2行第1列的值,第2行第2列的值,…},…};

A two-dimensional array temp two rows and two columns, and elements in the array has been initialized

//方式一
int[][] temp;
temp =new int[][]
{
    {1,2},{3,4}
};
//方式二
int[][] temp;
temp=new int [][]
{
    {new int(1),new int(2)},{new int(3),new int(4)}
};
//方式三
int[][] temp={{1,2},{3,4}};

Gets the element

A subscript to get

array[i][j];
int[][] temp={{1,2},{3,4},{5,6}};
System.out.println(temp[1][1]);//输出1

Traversal

Using the array's length property acquired number of array elements directly in a one-dimensional array. In the two-dimensional array, the length property directly acquired is the number of rows of the array, after the specified index plus length (eg array [0] .length) indicates that the bank has the number of elements, a nested loop to traverse the two-dimensional array

public static void main(String[] args)
{
    double[][] temp={{1,2},{3,4},{5,6}};
    for(int i=0;i<temp.length;i++)
    {
        for(int j=0;j<temp[i].length;j++)
        {
            System.out.println("temp["+i+"]["+j+"]");
        }
    }
}

Multidimensional Arrays

In addition to an array of one-dimensional and two-dimensional arrays, Java also supports more dimensional arrays, such as three-dimensional array, an array of four-and five-dimensional arrays and so on, they all belong to a multi-dimensional array
with three-dimensional array as an example to introduce multi-dimensional arrays, three dimensional arrays levels, three-dimensional array can be understood as a one-dimensional array, each element of its contents are two-dimensional array. And so on, you can get an array of any number of dimensions.
Statement multidimensional array initialization and use are similar to the two-dimensional array.

array[i][j][r];
int[][][] temp={{1,2,1},{3,4,3},{5,6,5}};
System.out.println(temp[1][1][1]);//输出1

Other similar basic two-dimensional array

Array Comparisons

Array requires not only an equal condition number of array elements must be equal, and requires the element corresponding to the location are equal. Arrays class provides equals () methods compare the entire array, arrayA first array for comparison, arrayB for comparing a second array

Arrays.equals(arrayA, arrayB);
int[] arr1={1,2,3};
int[] arr2={1,2,3};
int[] arr3={1,2,3,4};
Arrays.equals(arr1, arr2);//ture
Arrays.equals(arr1, arr3);//false

Find Array

Find an array refers to a query specified location from the array elements, or query the position of an element in the specified array. Use binarySearch Arrays class () method can be implemented lookup array, the method using the binary search method may be used to specify the search array for the specified object, the method returns the index to search for the element, binarySearch () method has a variety of heavy-duty Find forms to meet the needs of different types of arrays, commonly used in heavy-duty two forms.
Before making inquiries array, the array must be sorted (you can use sort () method). If you do not sort the array, the result is uncertain. If the array contains multiple elements with the specified value, it can not confirm which one finds

binarySearch(Object[] a,Object key);

a representation array to be searched, key represents the value to search for. If the key contained in the array, the index value is searched; otherwise, returns -1 or "- insertion point." Refers to the insertion point to insert a search key position in the array, i.e., a first element index greater than the key

int[] arr={1,2,3};
Arrays.binarySearch(arr,1);//查到,位置0
Arrays.binarySearch(arr,4);//查不到,返回-1

binarySearch(Object[] a,int fromIndex,int toIndex,Object key);

To find a represents an array, starting at the index fromIndex specified range (included at the beginning), index toIndex at the end of the specified range (not included at the end), key represents the element to search for

int[] arr={1,2,3};
Arrays.binarySearch(arr,0,2,1);//查到,位置0
Arrays.binarySearch(arr,0,1,3);//查不到,返回-1

Copies the array

There are four copies the array to achieve a method, respectively, using the class copyOf Arrays () method The arraycopy and copyOfRange () Method, System class () method and the class Object clone () method

copyOf()、copyOfRange()

copyOf () array is copied to a specified length

Arrays.copyOf(dataType[] srcArray,int length);

srcArray array to be expressed copy, length represents the length of the array after the new copy, copy the array used this method, a default start copying from the first source element of the array (index value 0), the length of the array will be the target length. If the length is greater than srcArray.length, the default value is employed to fill in the destination array (eg: int type array default value is 0); if the length is less than srcArray.length, is copied to the second length elements with index values ​​(length-1) i.e. stop.

int arr[]=new int[]{1,2,3};
int[] newArr=(int[])Arrays.copyOf(arr,4);//新数组1,2,3,0

Copy specified length copyOfRange () method will be specified array into a new array

Arrays.copyOfRange(dataType[] srcArray,int startIndex,int endIndex)

srcArray represents the source array; startIndex starting index indicates the start of copying, the start index of the target array will contain the corresponding elements, further, must be between srcArray.length in startIndex 0; endIndex index indicates the termination, the target is not included in the array termination element corresponding to the index, endIndex must be greater than or equal startIndex, may be greater than srcArray.length, if more than srcArray.length, the target array filled with default values

int arr[]=new int[]{1,2,3};
int[] newArr=(int[])Arrays.copyOf(arr,1,4);//新数组2,3,0

arraycopy()

The arraycopy () method is in a class java.lang.System

System.arraycopy(dataType[] srcArray,int srcIndex,int destArray,int destIndex,int length)

srcArray represents the source array; srcIndex indicates a start index of the source array; destArray represents a target array; destIndex indicates a start index of the target array; length represents the length of the array to be copied, length + srcIndex must be less than or equal srcArray.length, while the length + destIndex must be less than or equal destArray.length

int arr[]=new int[]{1,2,3};
int newArr[]==new int[]{4,5,6};
System.arraycopy(arr,0, newArr,2,3);//新数组4,2,6

clone()

clone () method may also be implemented replicate array. This method is a method in the class Object, an object can create a separate memory space. Since the array is an Object class, and therefore can be used to clone array object () method to copy the array

array_name.clone()
int[] targetArray=(int[])sourceArray.clone();

Sorting an array

Sort java.util.Arrays class () method to sort the array divided into the following two steps: introducing java.util.Arrays package. Use Armys.sort (array name) to sort the array syntax, collation is from small to large, that is, in ascending order.

int[] arr=new int[]{1,5,4,3,6,2};
Arrays.sort(scores);//输出 1,2,3,4,5,6

Bubble Sort

Bubble sort (Bubble Sort) array is one of the common sorting algorithm, the basic idea is that bubble sort: Comparative neighboring element values, if the condition on the switching element value, the smaller the value of the element moves to the front array, the larger the value of the element array is moved to the back (i.e. the exchange position of the two elements), such as array elements as the bubbles rise from the bottom to the top.

int[] arr={6,3,8,2,9,1};
for(int i=0;i<arr.length-1;i++){//外层循环控制排序趟数
      for(int j=0;j<arr.length-1-i;j++){//内层循环控制每一趟排序多少次
        if(arr[j]>arr[j+1]){
          int temp=arr[j];
          arr[j]=arr[j+1];
          arr[j+1]=temp;
        }
      }
    } 

Quick Sort

Quicksort (Quicksort) is an improvement of the bubble sort, quicksort basic idea is: a trip through sorting, the sorted data will be separated into two separate portions, wherein a portion of all of the data are further than a portion of all the data to small, then this method of data quickly sort the two parts separately, the entire sorting process can be recursively, thereby enabling the entire data becomes an ordered sequence.

int[] arr = {10,7,2,4,7,62,3,4,2,1,8,9,19};
public static void quickSort(int[] arr,int low,int high){
    int i,j,temp,t;
    if(low>high){
        return;
    }
    i=low;
    j=high;
    temp = arr[low];//temp就是基准位
    while (i<j) {//先看右边,依次往左递减
        while (temp<=arr[j]&&i<j) {
            j--;
        }
        while (temp>=arr[i]&&i<j) {//再看左边,依次往右递增
                i++;
        }
        if (i<j) {//如果满足条件则交换
            t = arr[j];
            arr[j] = arr[i];
            arr[i] = t;
         }
    }
    //最后将基准为与i和j相等位置的数字交换
    arr[low] = arr[i];
    arr[i] = temp;
    //递归调用左半数组
    quickSort(arr, low, j-1);
    //递归调用右半数组
    quickSort(arr, j+1, high);
}
quickSort(arr, 0, arr.length-1);

Selection Sort

Selected sorting method described above can also sort the elements of the array, but it is different from the bubble sort. Selection sort means each pass selected maximum (or minimum) of the data element from an element to be sorted, the order has been placed last sorted, until all the data elements to be sorted SEQUENCE drained

int[] number={13,15,24,99,4,1};
int index;
for(int i=1;i<number.length;i++)
{
    index=0;
    for(int j=1;j<=number.length-i;j++)
    {
        if(number[j]>number[index])
        {
            index=j;    //查找最大值
        }
    }
    int temp=number[number.length-i];
    number[number.length-1]=number[index];
    number[index]=temp;
}

Guess you like

Origin www.cnblogs.com/lilinfeng/p/10982991.html
Recommended