Java Data Structures and Algorithms (ii)--arrays

Source: Internet
Author: User
Tags array length

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:

Data type []  array name = new data type [array length];

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:

data type [] Array name = {Array element 1, array element 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.

Declares an array of 1, declares a length of 3, can only hold data of type int [] MyArray = new int[3];//declares an array of 2, declares an array element to be an array of type int. int [] MyArray2 = {n/a};

  ②, 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.

Declares an array, declares a length of 3, can only hold data of type int [] MyArray = new int[3];//assigns value to MyArray first element 1myarray[0] = 1;// Access the first element of 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.

Declare array 2, declaring an array element of type 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.

Package Com.ys.array;public class MyArray {//define an array private int [] intarray;//defines the actual effective length of the array private int elems;// Defines the maximum length of an array private int length;//default constructs an array of length 50 public MyArray () {elems = 0;length = 50;intarray = new Int[length];} constructor, initializes a length array of public MyArray (int length) {elems = 0;this.length = Length;intarray = new Int[length];} Gets the valid length of the array public int getsize () {return elems;} /** * Traverse the display element */public void display () {for (int i = 0; i < Elems; i++) {System.out.print (intarray[i]+ "");} System.out.println ();} /** * Add Element * @param value, assuming that the operator does not add duplicate elements, if there are duplicate elements will have an effect on subsequent operations. * @return Add successfully returns TRUE, the added element exceeds the range returned false */public boolean add (int value) {if (Elems = = length) {return false;} Else{intarray[elems] = value;elems++;} return true;} /** * Get element according to subscript * @param i * @return find subscript value in the array subscript valid range, return the element represented by subscript * Find subscript out of array subscript valid value, prompt access subscript out of bounds */public int get (int i) {if (i<0 | | I>elems) {System.out.println ("Access subscript out of Bounds");} return intarray[i];} /** * Find element * @param searchvalue * @return Find the element if present returns the subscript value if it does not exist, return 1 */public int find (int Searchvalue) {int i; for (i = 0; i < Elems; i++) {if (intarray[i] = = Searchvalue) {break;}} if (i = = Elems) {return-1;} return i;} /** * Delete element * @param value * @return returns False if the value you want to delete does not exist, otherwise returns true, delete succeeded */public boolean delete (int value) {int k = find (val UE); if (k = =-1) {return false;} Else{if (k = = elems-1) {elems--;} else{for (int i = k; i< elems-1; i++) {intarray[i] = intarray[i+1];elems--;}} return true;}} /** * Modify Data * @param oldValue Original value * @param newvalue New value * @return modification successfully Returns TRUE, modification failure returns false */public Boolean modify (int oldvalue,in T newvalue) {int i = 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:

Package Com.ys.test;import Com.ys.array.myarray;public class Myarraytest {public static void main (string[] args) {// Create a custom encapsulated array structure with an array size of 4MyArray arrays = new MyArray (4);//Add 4 elements respectively 1,2,3,4array.add (1); Array.add (2); Array.add (3); Array.add (4);//display array element Array.display ();//based on the subscript 0 element int i = array.get (0); System.out.println (i);//delete element of 4 array.delete (4);//Modify Element 3 to 33array.modify (3, +); 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

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.