Java Base Array

Source: Internet
Author: User
Tags array definition array length print format

What is an array, a set of data, a bunch of data:

The so-called array, is in the program design, in order to deal with the convenience, the same type of a number of variables organized in an orderly form of a data form. These sets of data of the same type in a certain order are called arrays. Each of the data in the array is called an array element, and the elements in the array are indexed to indicate where they are stored, starting at 0, with a step of 1, a bit like the line number of an Excel table, incrementing by line. It's like a hotel room.

=int[] ages; array must be initialized,
Basic data type:byte,short,int,long,float,double,char, Boolean Reference Data type: Class, interface, array. definition of-------------------------------------------------variable:   data type  variable name;   int Age   ; array definition:   Mode 1: array element type []  array name;    int [] ages; yes, you can. int[] as a data type, an array type of type int.   Mode 2: Array element type  array name [];     int ages[]; The------------------------------------------------------ array must be initialized before it can be used, because initialization means allocating space in memory.
Initialization of the array
Arrays in Java must be initialized before they can be used, so-called initialization allocates memory for array elements and assigns an initial value to each element. Initialize the array in two ways: static initialization; dynamic initialization; Regardless of how the array is initialized, once the initialization is complete, the length of the array is fixed and cannot be changed unless reinitialized. In other words, the array is fixed length.   the array is fixed-length: Once the array is initialized successfully, the number of elements in the array is pinned, cannot be changed, and can only be reinitialized if changes are required.
Static initialization of the array:

feature: It's up to us to set the initialization value for each array element, and the length of the array is determined by the system (JVM).

Grammar:

array element type []  new  array element type []{element 1, Element 2, element 3,.......};   Example:   intnew  int[]{1,3,5,7,9};   A simple notation, which must be declared immediately after initialization, cannot be declared after initialization:    int[] nums = {1,3,5,7,9};

Dynamic initialization of an array:

It is up to us to set the number of elements in the array (array length), and the initial value of each array element is determined by the system.

Grammar:

array element type []  new   array element type [length];    For example    :intnew  int[+]; -------------------------------------------------------------  intnew  int [5]{1,3,5,7,9}; // The notation is wrong, and static initialization and dynamic initialization cannot be used at the same time.

When to use static initialization, when to use dynamic initialization.

Static initialization is used when we know beforehand what data needs to be stored. When we don't know what data to store beforehand, we can only use dynamic initialization.

Basic operations for Arrays 1. Basic operation of arrays
       Get element:  element type variable =   array name [index];       Set element:  = value;       Traversing array elements: We recommend using a For loop to know the number of loops in advance.       Array Length:  int len = array name. length;  Length is a property, not a method.       Index range:  increments from 0 onwards.   [0, array name. length-1]

2: Operation Array Common exceptions:
nullpointerexception: null pointer exception (null reference).            When the array is not initialized, the array is manipulated directly        . NULL ;        System.out.println (bs.length)       arrayindexoutofboundsexception: Array index out-of-bounds exception.
3: Gets the maximum minimum element of the array (getmax,getmin).

4: Print array elements:
when printing an array directly, print out the hashcode value, such as [[email protected]       We do not like, we want to print the array, the elements of the array to        print out. = {"A", "B", "C", "D", "E"}; Define method print: The string representation is made up of an array of element lists, enclosed in square brackets ("[]"). Adjacent elements are separated by the character ","(comma and space). Print format: [A, B, C, D, E]

5: Array elements in reverse order
Original array: [A, B, C, D, E]        operation of        new arrays in reverse order: [E, D, C, B, A]

6: Element appears indexed (first/last), linear search.
int [] arr = {10,20,30,10,50,-30,10};         Gets the index of the first occurrence of element 10 in the arr array (indexOf   ):0          Gets the index of the last occurrence of element 10 in the arr Array (lastIndexOf):6

Array parameters of the Main method

The Main method is static decorated, which means that the invocation of the Hello class is used directly. At the bottom is the JVM through Hello.main (new  string[]{}); the String array parameter of the Main method, is actually exposed to the program runner, which is used to pass a data message to the program.

Multidimensional arrays
As I said earlier, an array is a collection of multiple data. int New int [] {1,3,5,7,9}; If you have more than one array now, I want to save multiple arrays in a collection, and how I should do that at this point. int [] arr1 = {n/a}; int [] arr2 = {4,5}; int [] Arr3 = {6}; Each of the above arrays as an element, the type of the element at this time is:int[].
Syntax for the array:
array element type [] array name; int []  newint[] []   {    arr1, arr2,arr3}; int []  newint[] []   {    {4,5},    {*}},    { 6}};
multidimensional Arrays: arrays in arrays, different from the C language syntax: array element type [] array name; understanding of multidimensional arrays int [3] [5]: two-dimensional array of three elements, one-dimensional array of 5 elements traversing the elements in a two-dimensional array understanding the value transfer mechanism of a two-dimensional array
one-dimensional arrays: Each element in an array is a value (the base type and the value of the reference type). Two-dimensional array: Each element in the array is an array. Three-dimensional arrays: Each element in an array is a two-dimensional array. ------------------------------------------------------------------------------- Strictly speaking, there is no concept of multidimensional arrays in Java, And the C language, commonly referred to as arrays in arrays.
Initialization of a two-dimensional array:

Static initialization:

int []  newint[] []   {    {4,5},    {6},     }};

Dynamic initialization:

int []  newint[3][5]; Creates a two-dimensional array of length 3, with each element (one-dimensional array) having a length of 5. int []  newint

N-loop nesting is required for n-dimensional arrays.

New syntax support for JAVA5 arrays
JAVA5 new syntax support for array:    1): Enhanced for Loop-foreach   2): Variable parameter of method
Enhanced for Loop-foreach:

Requirements: Define an array, using loops to iterate over each element in the group.

The action for using a For loop is as follows:

In fact, when we use the Loop iterative algebraic group, often do not care about the iteration variable (array index), there is no better way to iterate the elements of the algebraic group, only the array elements, not to manipulate the index of the array. Starting with Java5 (JDK1.5), Java provides a new syntax: Enhanced for Loop (foreach). Grammar:

 for (array element type variable  :   array name) {       loop body}

Looking at the bytecode with the anti-compilation tool, I find that foreach still uses the For Loop + index to manipulate the array at the bottom. We put the enhanced for loop, which is called the compiler's new feature ----> syntax sugar. The greatest sweetness of grammatical sugars is: Let developers write less, simpler code and do the same thing. -----------------------------------------------------------forLoop is more powerful than foreach. ------------------------------------------------------------ Use foreach If you are iterating over an array of elements without caring for the index of the arrays. -----------------------------------foreach has not finished ---> collection framework.

Variable parameters of the method:

Requirements: Write a method that counts the sum that is passed over using an array.

but in the heart    of the uncomfortable: 1): To find the sum of multiple numbers, I have to create an array to store the data    . 2): If more than the number is a change, for example, the sum of 3 numbers, becomes the sum of 5 numbers .... I still have to modify my array, but the array is fixed length. Speaking: I expect the method of calling sum to be called.

To solve this problem, you must use another new feature of JAVA5, the variable parameter of the method, that is, the number of arguments is variable.

The variable parameters of the method are actually a new feature of the syntax sugar, compiler level, which makes it easier for developers to write code. The variable parameter of a method is an array type. The variable parameter must be the last parameter of the method, avoiding the ambiguity of the parameter.  Inference: The method has a maximum of only one variable parameter.

Copy of array elements

Array Copy: Copies an array from the specified source array, starting at the specified location and ending at the specified position in the destination array. A sub-sequence of the array component is copied from the source array referenced by SRC to the target array of dest references. The number of the component being copied is equal to the length parameter. the components in the source array that are positioned between Srcpos to Srcpos +length-1 are copied to the Destpos to destpos+length-1 position in the destination array, respectively .  publicstaticvoid arraycopy (intintint[] dest,int  int  length) {}

Java comes with array tool class arrays
array of algorithmic operations, used too often, sun company directly in the JDK provides an array of tool classes (Arrays). Java.util.Arrays class: int BinarySearch (type[] arr,type key)    uses dichotomy to find an element in an array and returns its index, if no negative number is found. void Sort (type[] arr)    sorts the specified array using the Fast method after tuning. String toString (type[] arr)    Returns a string representation of the contents of the specified array.  publicstaticint newlength)    copies the specified array, intercepts, or fills with 0 (if necessary) so that the copy has the specified length. --------------------------------------------- Use note: Must be java.util.Arrays. Method (parameter);

Java Base Array

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.