Data structure (i) _ array

Source: Internet
Author: User
Tags array length

Basic knowledge of arrays

The array is one of the important data structures for each programming language, of course, the implementation and processing of the different language arrays are not the same.
The array provided in the Java language is used to store the same type elements of a fixed size.

public class Demo1 {    public static void main(String[] args) {        // 定义一个数组,保存五名学生的成绩        int[] scores = { 78, 93, 97, 84, 63 };        // 输出数组中的第二个成绩        System.out.println("数组中的第2个成绩为:" + scores[1]);    }}
Basic use of arrays

1. Declaring arrays

Syntax: data type [] array name;

Or a data type array name [];

Where the array name can be any valid variable name, such as:

2. Allocate space

In short, it is the maximum number of elements that can be stored in the specified array

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

Where the array length is the number of elements that can be stored in an array, such as:

In other words, we can also combine the above two steps to allocate space for it while declaring an array, such as:

3. Assign Value

After allocating space, the data can be placed into the array, and the elements in the array are accessed by subscripts, such as storing student scores in the scores array

4. Working with data in arrays

We can manipulate and manipulate the array after the assignment, such as getting and outputting the values of the elements in the array

Another way to create an array directly in Java is to combine declaring an array, allocating space, and assigning values, such as

It is equivalent to:

Using loops to manipulate arrays in Java
public static void main(String[] args) {        // 定义一个数组,保存五名学生的成绩        int[] scores = { 78, 93, 97, 84, 63 };        //for循环打印        for (int i = 0; i < scores.length; i++) {            System.out.print(scores[i]+"  ");        }        System.out.println();        //foreach打印        //foreach是for语句的特殊简化版本,在遍历数组、集合时, foreach更简单便捷。        //for(元素类型  变量:遍历对象){        //执行的代码        //}        for (int i : scores) {            System.out.print(i+"  ");        }    }

Execution results
78 93 97) 84 63
78 93 97) 84 63

Programming exercises
package com.zhb;public class Demo1 {    public static void main(String[] args) {        int[] nums = new int[] { 61, 23, 4, 74, 13, 148, 20 };        int max = nums[0]; // 假定最大值为数组中的第一个元素        int min = nums[0]; // 假定最小值为数组中的第一个元素        double sum = 0;// 累加值        double avg = 0;// 平均值        for (int i = 0; i < nums.length; i++) { // 循环遍历数组中的元素            // 如果当前值大于max,则替换max的值            if(nums[i]> max){                max = nums[i];            }            // 如果当前值小于min,则替换min的值            if(nums[i]< min){                min = nums[i];            }            // 累加求和            sum+=nums[i];        }        // 求平均值        avg = sum/nums.length;        System.out.println("数组中的最大值:" + max);        System.out.println("数组中的最小值:" + min);        System.out.println("数组中的平均值:" + avg);    }}

Output results
Maximum value in array: 148
Minimum value in array: 4
Average of the array: 49.0

Using the Arrays class to manipulate arrays in Java

The Arrays class is a tool class provided in Java, in the Java.util package. The class contains methods for manipulating arrays directly, such as sorting, searching, and so on.

package com.zhb;import java.util.Arrays;public class Demo1 {    public static void main(String[] args) {        // 定义一个字符串数组        String[] hobbys = { "sports", "game", "movie" };                // 使用Arrays类的sort()方法对数组进行排序        Arrays.sort(hobbys);                    // 使用Arrays类的toString()方法将数组转换为字符串并输出        System.out.println( Arrays.toString(hobbys) );    }}

Execution results
[Game, movie, sports]

Building dynamic arrays

In fact, this is similar to the implementation of the ArrayList class simulation. This is just a simplified section. The main code

First, we first construct a dynamic array of type int
    • The default capacity here is 10 and ArrayList, which also tells us that ArrayList default capacity is 10, where the Ali protocol mentions that when using a collection, you specify the collection initial value size
/** * Dynamic int Array * * @author: Curry * @Date: 2018/8/2 */public class Array {private int[] data;    private int size; /** * constructor function.         The capacity of the incoming array capacity constructs an array * * @param capacity */public array (int capacity) {data = new int[capacity];    size = 0;    }/** * No parameter constructor, default capacity is ten */public Array () {this (10);    }/** * Gets the number of elements in the array * * @return */public int getsize () {return size;    }/** * Gets the array capacity * * @return */public int getcapacity () {return data.length;    }/** * Returns whether the array is empty * * @return */public boolean isEmpty () {return size = = 0;    /** * add element to array last * * @param e */public void addlast (int e) {Add (size, E);    }/** * Adds an element to the array at the end of * * @param e */public void AddFirst (int e) {Add (0, E); }/** * Adds element e * * @param index * @param e */public void Add (int index) to the index position.int e) {//Determine if Index is legal if (Index < 0 | | index > size) {throw new Illegalargumentexceptio        N ("index is Error");        }//Determine if the capacity exceeds if (size = = Data.length) {throw new IllegalArgumentException ("Array is full");        }//The value after index is moved back for (int i = size-1; I >= index; i--) {data[i + 1] = Data[i];        }//assignment to index position data[index] = e;    size++; /** * Gets the value of the index position * * @param index * @return */public int get (int index) {//Judgment Inde        X is legal if (Index < 0 | | Index >= size) {throw new IllegalArgumentException ("Index is Error");    } return Data[index];            } public void set (int index, int e) {//To determine if index is legal if (Index < 0 | | Index >= size) {        throw new IllegalArgumentException ("Index is Error");    } Data[index] = e;  }/** * Find if there are elements in the array * * @param e   * @return */public Boolean contains (Int. e) {for (int i = 0; i < size; i++) {if (Data[i]            = = e) {return true;    }} return false; }/** * finds the index of element e in the array * * @param e * @return */public int find (int. e) {for (int i = 0; i < size;            i++) {if (data[i] = = e) {return i;    }} return-1; }/** * Delete the value indexed as index * * @param index * @return */public int remove (int index) {//Judge in        Whether Dex is legal if (Index < 0 | | Index >= size) {throw new IllegalArgumentException ("Index is Error");        } int ret = Data[index];        for (int i = index; i < size; i++) {Data[i] = data[i + 1];        } size--;    return ret;    }/** * Deletes the first element * * @return */public int removefirst () {return remove (0); }/** * Delete last element * * @rEturn */public int removelast () {return remove (size-1);        }/** * Delete elements in array * * @param e */public void removeelement (int e) {int index = find (e);        if (Index! =-1) {remove (index);        }} @Override public String toString () {StringBuilder res = new StringBuilder ();        Res.append (String.Format ("array:size =%d, capacity =%d\n", size, data.length));        Res.append ("[");            for (int i = 0; i < size; i++) {res.append (data[i]);            if (i! = size-1) {res.append (",");        }} res.append ("]");    return res.tostring (); }}
Modify the above code to add generics
    • Note: This adds the Resize method for expansion, because the underlying is also an array implementation, so when the length of the array is not enough, you need to expand, where the expansion is twice times the original length. 1.5 times times in ArrayList
/** * Using generics * * @author: Curry * @Date: 2018/8/2 */public class Array1<e> {private e[] data;    private int size; /** * constructor function. The capacity of the incoming array capacity constructs an array * * @param capacity */public Array1 (int capacity) {data = (e[]) New object[        Capacity];    size = 0;    }/** * No parameter constructor, default capacity is ten */public Array1 () {this (10);    }/** * Gets the number of elements in the array * * @return */public int getsize () {return size;    }/** * Gets the array capacity * * @return */public int getcapacity () {return data.length;    }/** * Returns whether the array is empty * * @return */public boolean isEmpty () {return size = = 0;    /** * add element to the array last * * @param e */public void AddLast (E e) {Add (size, E);    }/** * Adds an element to the array at the end of * * @param e */public void AddFirst (E e) {Add (0, E); /** * add element to index position e * * @param index * @param e */public void add(int index, E e) {//Determine if Index is legal if (Index < 0 | | index > size) {throw new IllegalArgumentException ("Inde        X is Error ");        }//Determine if the capacity exceeds if (size = = Data.length) {Resize (2 * data.length);        }//The value after index is moved back for (int i = size-1; I >= index; i--) {data[i + 1] = Data[i];        }//assignment to index position data[index] = e;    size++; /** * Gets the value of the index position * * @param index * @return */public E get (int index) {//Determine index        Legal if (Index < 0 | | Index >= size) {throw new IllegalArgumentException ("Index is Error");    } return Data[index]; } public void set (int index, E e) {//Determine if Index is legal if (Index < 0 | | Index >= size) {th        Row new IllegalArgumentException ("Index is Error");    } Data[index] = e;   }/** * Find out if there are elements in the array * * @param e * @return * * Public Boolean contains (E-e) {for (int i = 0; i < size; i++) {if (Data[i].equals (e)) {            return true;    }} return false; /** * Find the index of element e in the array * * @param e * @return */public int find (e e) {for (int i = 0; i < size;            i++) {if (Data[i].equals (e)) {return i;    }} return-1; }/** * Delete the value indexed as index * * @param index * @return */public E remove (int index) {//Judge Inde        X is legal if (Index < 0 | | Index >= size) {throw new IllegalArgumentException ("Index is Error");        } E ret = Data[index];        for (int i = index; i < size; i++) {Data[i] = data[i + 1];        } size--;        Data[size] = null;    return ret;    }/** * Delete the first element * * @return */public E Removefirst () {return remove (0);     }/** * Delete last element ** @return */public E Removelast () {return remove (size-1);        }/** * Delete elements in array * * @param e */public void removeelement (e e) {int index = find (e);        if (Index! =-1) {remove (index);        }} @Override public String toString () {StringBuilder res = new StringBuilder ();        Res.append (String.Format ("array:size =%d, capacity =%d\n", size, data.length));        Res.append ("[");            for (int i = 0; i < size; i++) {res.append (data[i]);            if (i! = size-1) {res.append (",");        }} res.append ("]");    return res.tostring (); }/** * Expansion * * @param newcapacity */private void resize (int newcapacity) {e[] NewData = (e[        ]) New object[newcapacity];        for (int i = 0; i < data.length; i++) {newdata[i] = Data[i];    } data = NewData; }}

In fact, the dynamic array written here is also implemented in a simple ArrayList class.

Data structure (i) _ array

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.