Java Data Structures and Algorithms (ii)--arrays

Source: Internet
Author: User

On the previous blog we briefly introduced the concept of data structure and algorithm, it is normal to blur, and then slowly through the concrete examples to introduce. This blog we introduce the originator of data structure-arrays, can say that arrays can almost represent all the data structure, in each programming language, arrays are important data structure, of course, each language array of implementation and processing is not the same, but the essence is used to store data structure, Here we take the Java language as an example to detail the use of arrays in the Java language.

1. Introduction to Java Arrays

In Java, arrays are used to hold collections of the same data type, and note that only the same data type can be stored.

  Declaration of ①, array

  The first way:

1 数据类型 []  数组名称 = new数据类型[数组长度];

Here [] can be placed in front of the array name, or can be placed after the array name, we recommend to put in front of the array name, so that it appears that the data type [] is obviously an array type, and placed after the array name, it is not so intuitive.

  The second way:

1 数据类型 [] 数组名称 = {数组元素1,数组元素2,......}

This way the array is declared and the array's elements are given directly, and the size of the array is determined by the number of array elements given.

1234 //声明数组1,声明一个长度为3,只能存放int类型的数据int[] myArray = new int[3];//声明数组2,声明一个数组元素为 1,2,3的int类型数组int[] myArray2 = {1,2,3};

  ②, accessing array elements, and assigning values to array elements

Array is the existence of subscript index, through the subscript can get the element of the specified position, the array is starting from 0, that is, the subscript 0 corresponds to the 1th element in the array, it is convenient to access the elements in a set of arrays.

Declaration of the preceding array the second way, we declare the array, but also the initialization of the assignment.

123456 //声明数组,声明一个长度为3,只能存放int类型的数据int[] myArray = newint[3];//给myArray第一个元素赋值1myArray[0] = 1;//访问myArray的第一个元素System.out.println(myArray[0]);

Above the MyArray array, we can only assign a value of three elements, that is, subscript from 0 to 2, if you visit myarray[3], then the group subscript out of bounds exception.

  ③, array traversal

  The array has a length property, which is the size of the record array, and we can use the length property to iterate through the array.

12345 //声明数组2,声明一个数组元素为 1,2,3的int类型数组int[] myArray2 = {1,2,3};for(int i = 0; i < myArray2.length ; i++){    System.out.println(myArray2[i]);}

  

2. Implement data structure with class encapsulation array

Previous blog We introduced a data structure that must have the following basic features:

  ①, how to insert a new data item

②, how to find a particular data item

③, how to delete a specific data item

④, how to iterate over each item of data for display or other action

  And we know the simple use of arrays, and now encapsulate an array with the idea of class, implementing the four basic functions above:

PS: Assuming that the operator does not add duplicate elements, there is no consideration of repeating elements, if you add duplicate elements, the subsequent search, delete, modify and so on will only be valid for the first occurrence of the element.

 PackageCom.ys.array; Public classMyArray {//define an array    Private int[] intarray; //defines the actual effective length of an array    Private intElems; //defines the maximum length of an array    Private intlength; //constructs an array of length 50 by default     PublicMyArray () {Elems= 0; Length= 50; Intarray=New int[length]; }    //constructor, initializes an array of length     PublicMyArray (intlength) {Elems= 0;  This. length =length; Intarray=New int[length]; }         //gets the effective length of the array     Public intGetSize () {returnElems; }         /*** Traversing display elements*/     Public voiddisplay () { for(inti = 0; i < Elems; i++) {System.out.print (Intarray[i]+" ");    } System.out.println (); }         /*** add Element *@paramvalue, assuming that the operator does not add duplicate elements, if there are duplicate elements that will have an effect on subsequent operations. * @return Add successfully returns TRUE, the added element exceeds the range returned false*/     Public BooleanAddintvalue) {        if(Elems = =length) {            return false; }Else{Intarray[elems]=value; Elems++; }        return true; }         /*** Get the element according to the subscript *@paramI * @return find subscript value in the array subscript valid range, return the element represented by the subscript * Find subscript is outside the array subscript valid value, prompt to access subscript out of bounds*/     Public intGetinti) {        if(i<0 | | i>Elems) {System.out.println ("Access subscript out of bounds"); }        returnIntarray[i]; }    /*** Find elements *@paramSearchvalue * @return Lookup element returns the subscript value if it exists, or 1 if it does not exist*/     Public intFindintsearchvalue) {        inti;  for(i = 0; i < Elems; i++){            if(Intarray[i] = =searchvalue) {                 Break; }        }        if(i = =Elems) {            return-1; }        returni; }    /*** Delete element *@paramValue * @return returns False if the value to be removed does not exist, otherwise true, delete succeeded*/     Public BooleanDeleteintvalue) {        intK =find (value); if(k = =-1){            return false; }Else{            if(k = = Elems-1) {Elems--; }Else{                 for(inti = k; i< elems-1; i++) {Intarray[i]= Intarray[i+1]; Elems--; }            }            return true; }    }    /*** Modify Data *@paramoldvalue Original Value *@paramnewvalue New value * @return modification succeeded returns true, the modification failed to return false*/     Public BooleanModifyintOldValue,intnewvalue) {        inti =find (OldValue); if(i = =-1) {System.out.println ("Data that needs to be modified does not exist"); return false; }Else{Intarray[i]=NewValue; return true; }    } }

Test:

 Packagecom.ys.test;ImportCom.ys.array.MyArray; Public classMyarraytest { Public Static voidMain (string[] args) {//Create a custom encapsulated array structure with an array size of 4MyArray array =NewMyArray (4); //add 4 elements, respectively, 1,2,3,4Array.add (1); Array.add (2); Array.add (3); Array.add (4); //displaying array elementsArray.display (); //according to the element of subscript 0        inti = array.get (0);        System.out.println (i); //Remove 4 ElementsArray.delete (4); //Modify element 3 toArray.modify (3, 33);    Array.display (); } }

Printing results are:

  

3, analysis of the limitations of the array

Through the above code, we find that the array is able to complete a data structure of all the functions, and it is not difficult to implement, that the data can do all the work, we actually do not use it to do all the data storage? There must be a reason for that.

Analysis of the limitations of arrays:

①, insert fast, for unordered arrays, the arrays we implement above are unordered, that is, the elements are not arranged in a large or small or a specific order, but in the order in which they are inserted. An unordered array adds an element simply by adding an element at the end of the array, but the ordered array is not necessarily, it needs to be inserted at the specified location.

②, look slow, of course, if the subscript to find is very fast. But usually we look at the value of the element, given an element value, for an unordered array, we need to start with the first element of the array, and know that the element is found. An ordered array can be found by a particular algorithm faster than without an array, and we'll talk about sorting algorithms later on.

③, delete slowly, according to the value of the element is deleted, we need to find the location of the element, and then the value behind the element to move the whole forward one position. It also takes a lot more time.

④, arrays once created, the size is fixed, you cannot dynamically expand the number of elements of the array. If you initialize to a very large array size, it will be wasted memory space, if it is small, the number of subsequent data added and not to go in.

Obviously, although the array is inserted fast, but the search and delete are slow, so we do not use an array to store all the data, that there is no structure to insert, find, delete is very fast, but also dynamically expand the size of the storage, the answer is yes, but this is based on a very complex algorithm, We will explain it in detail later.

4. Summary

This blog we explain the basic use of arrays, and the Java language class to implement an array of data structure, but we analyze the data structure, found that there are many performance problems, and then explain the other data structures to see how those data structures are dealing with these problems. Of course, before explaining the data structure, the next blog we will briefly introduce several commonly used sorting algorithms.

Java Data Structures and Algorithms (ii)--arrays

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.