Java array, java Array

Source: Internet
Author: User
Tags array definition array example

Java array, java Array

Array Overview:

1. Arrays can be seen as a combination of multiple data types for unified management of these data.

2. array variables belong to the reference type. Arrays can also be considered objects. Each element in the array is equivalent to the member variables of the object.

3. The elements in the array can be of any type, including basic type and reference type.

One-dimensional array declaration:

1. One-dimensional array declaration method:

Type var []; or type [] var;

For example:

Int a1 []; int [] a2; double B []; Person [] p1; String s1 [];

2. When declaring an array in java, you cannot specify its length (number of elements in the array). For example:

Int a [5]; // invalid

Create an array object:

1. Use the keyword "new" in java to create an array object. format:

Array name = new array element type [number of array elements];

For example:

public class TestArray{    public static void main(String args[]){        int[] arr;        arr = new int[5];        for(int i=0;i<5;i++){            arr[i] = i;            System.out.println(arr[i]);        }    }}

2. elements are data of the reference type (Note: Each element in an array of the referenced data type needs to be instantiated)

For example:

Public class TestArray {public static void main (String args []) {Date [] date; date = new Date [3]; for (int I = 0; I <3; I ++) {date [I] = new Date (, 25); System. out. println (date [I]. year + "year," + date [I]. month + "month," + date [I]. day + "day! ") ;}} Class Date {int year, month, day; public Date (int year, int month, int day) {this. year = year; this. month = month; this. day = day ;}}

 Array initialization:

1. Dynamic initialization:

The array definition is separated from the operations for allocating space and assigning values to array elements. For example:

Public class TestArray {public static void main (String args []) {int [] arr = new int [3]; // array definition arr [0] = 1; // array initialization arr [1] = 2; arr [2] = 3; Date [] date = new Date [3]; // array definition date [0] = new Date (, 25); // array initialization date [1] = new Date (, 25 ); date [2] = new Date (, 25);} class Date {int year, month, day; public Date (int year, int month, int day) {this. year = year; this. month = month; this. day = day ;}}

2. Static Initialization

When defining an array, allocate space and assign values to the array elements. For example:

public class TestArray{    public static void main(String args[]){        int a[] = {1,2,3};        Date[] date = {new Date(2014,10,25), new Date(2014,10,26), new Date(2014,10,27)};    }}class Date{    int year,month,day;    public Date(int year,int month,int day){        this.year = year;        this.month = month;        this.day = day;    }}

3. Default initialization of array elements:

The element of an array is equivalent to a member variable of the class. Therefore, after the array is allocated space, each element is implicitly initialized according to the rules of the member variable. For example:

public class TestArray{    public static void main(String args[]){        int[] a = new int[3];        Date[] date = new Date[3];        System.out.println(a[2]);        System.out.println(date[2]);    }}class Date{    int year,month,day;    public Date(int year,int month,int day){        this.year = year;        this.month = month;        this.day = day;    }}

Array element reference:

1. Define and use the new operator to allocate space for each element in the array. the reference method of the array element is as follows:

①. ArrayName [index]

Index is the subscript of an array element, which can make the integer always bright or an integer expression. For example:

A [3], B [I], c [6 * I];

② The subscript of the array element starts from 0; the valid subscript value range of the array whose length is n is:

0 ~ N-1;

2. Each array has an attribute lendth (Note: Here length is an attribute, not a method, and there is no parentheses (). Here we particularly note that it is used to match the length () of String () specifies the length of a method, for example:

A. length is the length of array a (number of elements)

Note:

Public static void main (String args []) {}

The main function in each class also has an array named srgs. Why is this array used? This array is like injecting all in ipconfig-all in the command line. We can enter java TestArray (class name), aa, bbb and several parameters. Then you can see it in the code output.

Note (basic package type ):

The basic type of conversion class. The basic type is allocated in the stack memory, and the packaging class is allocated in the heap space.

Basic types of packages include: boolean --- boolean, Byte --- byte, Character --- char, Double --- double, Float --- float, Integer --- int, Long --- long, Short --- short we usually use parsexxx () to convert the string type to the desired data type. You can also use the valueOf () method of the string type to convert the desired data type to the string type.

The following is an example of using the args [] parameter with the basic type packaging class for calculation +-x /:

public class TestArgs{    public static void main(String args[]){        if(args.length<3){            System.out.println("error~~~");            System.exit(0);        }        double  b1 = Double.parseDouble(args[0]);        double  b2 = Double.parseDouble(args[2]);        double  b = 0;        if(args[1].equals("+")){            b = b1 + b2;        }else if(args[1].equals("-")){            b = b1-b2;        }else if(args[1].equals("x")){            b = b1*b2;        }else if(args[1].equals("/")){            b = b1/b2;        }else{            System.out.println("error operation!!!");        }        System.out.println(b);    }}

The following is an example of using ars to input 10 numbers and sorting them in ascending order:

public class TestSortInt{    public static void main(String args[]){        int[] a = new int[args.length];        for(int i=0; i<args.length; i++){            a[i] = Integer.parseInt(args[i]);        }        int k,temp;        for(int i=0; i<a.length; i++){            k = i;            for(int j=i+1; j<a.length; j++){                if(a[k]>a[j]){                    k=j;                 }            }            if(k!=i){                temp = a[i];                a[i] = a[k];                a[k] = temp;            }        }        for(int i=0; i<a.length; i++){            System.out.print(a[i] + " ");        }    }}

In the following example, a date type is installed in the array for sorting, and Bubble Sorting is used.

public class TestDateSort{    public static void main(String args[]){        Date[] date = new Date[5];        date[0] = new Date(2006,5,4);        date[1] = new Date(2006,7,4);        date[2] = new Date(2008,5,4);        date[3] = new Date(2004,5,9);        date[4] = new Date(2006,5,4);                bubbleSort(date);                for(int i=0; i < date.length; i++){            System.out.println(date[i]);        }    }    public static Date[] bubbleSort(Date[] a){        int len = a.length;        for(int i=len; i>=1; i--){            for(int j=0; j<i-1; j++){                if(a[j].compare(a[j+1])>0){                    Date temp = a[j+1];                    a[j+1] = a[j];                    a[j] = temp;                }            }        }        return a;    }}class Date{    private int year,month,day;    public Date(int year,int month,int day){        this.year = year;        this.month = month;        this.day = day;    }    public int compare(Date date){        return year>date.year?1               :year<date.year?-1               :month>date.month?1               :month<date.month?-1               :day>date.day?1               :day<date.day?-1               :0;    }    public String toString(){        return "year,month,day ---- " +year+" - "+month+" - "+day;    }}

In the following example, we use an array to play the game with the number three and the number three. That is to say, a lot of people are in a circle, and the Number One, Two, Three is counted into three, the remaining persons continue counting from 1 again, knowing the last person left. We use arrays to find who the last person is?

In this example, we assume that there are 500 people in a number in a circle, and the subscript is 435. This person wins, that is, 436th people win !~~~

public class Count3Quit{    public static void main(String args[]){        boolean[] arr = new boolean[500];        for(int i=0; i<arr.length; i++){            arr[i] = true;        }                int leftCount = arr.length;        int count = 0;        int index = 0;        while(leftCount > 1){            if(arr[index] == true){                count++;                if(count == 3){                    count = 0;                    arr[index] = false;                    leftCount --;                }            }            index ++;            if(index == arr.length){                index=0;            }        }                for(int i=0; i<arr.length; i++){            if(arr[i]==true){                System.out.println(i);            }        }    }    }

With arrays, we can design various sorting algorithms. Then, when sorting out the order, we can design a variety of search algorithms. Next, we use arrays to implement a simple binary search algorithm.

public class TestSearch{    public static void main(String args[]){        int[] a = {12,23,41,53,24,57,32,52,98,43,19,73};        int postion = binarySearch(a,57);        System.out.println(postion);    }    public static int binarySearch(int[] a, int searchNum){                if(a.length==0)return -1;                int startFlag = 0;        int endFlag = a.length-1;        int m = (startFlag+endFlag)/2;        while(startFlag<=endFlag){            if(a[m] == searchNum){                return m;            }else if(a[m]<searchNum){                startFlag = m+1;            }else if(a[m]>searchNum){                startFlag = m+1;            }            m = (startFlag+endFlag)/2;        }        return -1;    }}

 Two-dimensional array:

1. A two-dimensional array can be regarded as an array with arrays as elements. For example:

Int a [] [] = {1, 2}, {3, 4, 5, 6}, {7, 8, 9 }};

2. The declaration and initialization of multi-dimensional arrays in java should be performed in the order from high-dimensional to low-dimensional. For example:

Int a [] [] = new int [3] [];

A [0] = new int [2];

A [1] = new int [4];

A [2] = new int [3];

Int t1 [] [] = new int [] [4]; // This statement is invalid.

Two-dimensional array initialization:

   1. Static initialization:

Int intA [] [] = {1, 2}, {2, 3}, {3, 4, 5 }};

Int intB [3] [2] = {1, 2}, {, 2, 3}, {4, 5}; // illegal declaration method

2. Dynamic initialization:

Int a [] [] = new int [3] [5];

Int B [] [] = new int [3] [];

B [0] = new int [2];

B [1] = new int [3];

B [2] = new int [5];

Two-dimensional array example:

  

public class Test{    public static void main(String args[]){        int a[][] = {{1,2},{3,4,5,6},{7,8,9}};                for(int i=0; i<a.length; i++){            for(int j=0; j<a[i].length; j++){                System.out.print("["+i+"]"+"["+j+"]="+a[i][j]+"  ");            }            System.out.println();        }    }}

Two-dimensional array example (reference type two-dimensional array ):

Public class Test {public static void main (String args []) {String s [] []; s = new String [3] []; s [0] = new String [2]; s [1] = new String [3]; s [2] = new String [2]; for (int I = 0; I <s. length; I ++) {for (int j = 0; j <s [I]. length; j ++) {s [I] [j] = new String ("My location is:" + I + "," + j);} System. out. println () ;}for (int I = 0; I <s. length; I ++) {for (int j = 0; j <s [I]. length; j ++) {System. out. print (s [I] [j] + "");} System. out. println ();}}}

Copy an array:

1. Use static methods of the java. lang. system class

Public static void arrayCopy (object src, int srcPos, object dest, int destPos, int length ){}

2. You can use the src array to copy the length element starting with the srcPos entry to the lenght element starting with the destPos entry of the target array.

3. If the number of source data exceeds the target array boundsexception, an indexoutofboundception exception is thrown.

Data copy example:

import java.lang.System;public class TestArrayCopy{    public static void main(String args[]){        String[] s = {"Microsoft","IBN","Sun","Oracle","Apple"};        String[] sBak = new String[6];        System.arraycopy(s,0,sBak,0,s.length);                for(int i=0;i<sBak.length;i++){        System.out.print(sBak[i]+" ");        }        System.out.println();                int[][] intArray = {{1,2},{1,2,3},{3,4}};        int[][] intArrayBak = new int[3][];        System.arraycopy(intArray,0,intArrayBak,0,intArray.length);        intArrayBak[2][1] = 100;                for(int i=0;i<intArray.length;i++){            for(int j=0;j<intArray[i].length;j++){                System.out.print(intArray[i][j]+" ");            }            System.out.println();        }    }}

So far, the basic knowledge of data is finished. Learning arrays, more importantly, learning sorting algorithms for us ~~ Lay the foundation, and this is more important !!!

 


Unknown java Array

For (int I = 0; I <s. length; I ++)
First, the for statement is a loop statement,
I = 0 indicates that the subscript starts from 0, that is, processing starts from the first element of the array,
I <s. length indicates the condition for jumping out of the loop. When the current I value <s. length is the length of the I <array, the content of the for statement is executed.
I ++ indicates that after a loop is executed, I add 1, that is, the next element of the array is processed every time the loop is executed.
A multi-dimensional array is an array with an index group latitude greater than 1.
An array has only one subscript, which is called a "one-dimensional array", such as S [3]. A two-dimensional array uses two subscripts to represent S [4] [5]. it can be understood as a vector composed of four row vectors or a vector composed of n column vectors, in a two-dimensional array, each element S [I] [j] is the element of column j of the row of row I, and there are three-dimensional arrays in turn.
Composite array: Generally, an array stores basic types such as int and char, but can also store classes or other data structures.

The sum of all elements in a java two-dimensional array (3*3)

Int a [] [] = new int [3] [3];
// Initialize the Array
Int sum = 0;
For (int I = 0; I <3; I ++)
{
For (int j = 0; j <3; j ++)
{
Sum = sum + a [I] [j];
}
}

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: 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.