Java collections Getting Started Series (six)

Foreword

Next we enter a set of learning, learning about the collection will be divided based learning, to explain the data structure, source code analysis into three parts to explain.

Starter collection

We have an example to explain the collection of entry, when we go to school physical education, physical education teacher first told us how many students would stand in a pair to register, and then the dissolution of freedom rest, ha ha. Physical education teacher asked us to stand in a pair, this time like array for data storage, we need to assume a physical education teacher five people stand in a pair, so that it corresponds to the capacity of the array initialization Once you have the capacity, then it is in the requires local stations to the specified location, which is like adding elements to the array, well then we in the Java language to achieve this requirement. First we define a class queue, based on object-oriented package thinking, we provide a method of operating outside, so in such an array as defined in private, and then define the number of elements in the set attributes, as follows:

public class QueueDemo {

    private int Size;

    private Integer[] Elements;

}

Based on our analysis, we follow the stand 5 as a pair, so when we initialize class queuing capacity to initialize the array, that is to say we initial capacity in the constructor, as follows:

public  class QueueDemo { 

    // array size 
    Private  int Size; 

    // array 
    Private Integer [] Elements; 
    
    // initialize the array capacity 
    public QueueDemo ( int Capacity) { 
        Elements = new new Integer [Capacity]; 
    } 

}

We have initial capacity of it, then it is correspondence students began to line up at this time is to add elements correspond to the array, so we added a packaging method, each add an element of the array size is incremented by 1, as follows:

    // 添加元素
    public void Add(Integer element) {
        Elements[Size] = element;
        Size++;
    }

Corresponding to each step, we have to traverse the print elements in the array, so next we rewrite toString method, as follows:

  // 重写toString打印元素
    @Override
    public String toString() {
        int length = Elements.length;
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < length; i++) {
            sb.append(Elements[i]);
            if (i != length - 1) {
                sb.append(",");
            }
        }
        return sb.toString();
    }

We completed the first step students line up, then we instantiate the class and add the above line elements (students name while waiting in line when we will be seen as an element), and finally print elements, as follows:

public class Main {

    public static void main(String[] args) {
        QueueDemo demo = new QueueDemo(5);
        demo.Add(1);
        demo.Add(2);
        demo.Add(3);
        demo.Add(4);
        demo.Add(5);
        System.out.println(demo);
    }
}

When the students lined up, a physical education teacher found the students line up of varying height, then it is exchanged between the students and the students according to height, which also corresponds to our approach needs to insert elements of the package, because we initialize the array capacity 5, when we insert an element at the specified index, then print element array bound exception is thrown, the array is related to the capacity expansion, we define the time being in the process of inserting the specified index of the element, as follows:

public void Insert(int index, Integer element) {
        
}

When lined up in accordance with the height, physical education teacher, just think a row of four people, the remaining one person to another to go, this will delete the corresponding element in the array, the same method we define deleted when we delete elements in the array, you need to delete elements of the element are moved forward one, while the last position is empty, the array size is reduced one, as follows:

// 删除元素
public void Remove(Integer element) {
        int index = GetIndex(element);
        for (int i = index; i < Elements.length - 1; i++) {
            Elements[i] = Elements[i + 1];
        }
        Elements[Size - 1] = null;
        Size--;
}

Next we delete and print elements, as follows:

        // delete elements 
        demo.Remove (3 ); 
        System.out.println (Demo);

 Because we will be the last element of the array is set to empty, so should delete print, we continue to transform rewrite toString method, as follows:

    @Override
    public String toString() {
        int length = Elements.length;
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < length; i++) {
            if (Elements[i] == null) {
                continue;
            }
            sb.append(Elements[i]);
            if (i != length - 1) {
                sb.append(",");
            }
        }
        if (sb.charAt(sb.length() - 1) == ',') {
            sb.delete(sb.length() - 1, sb.length());
        }
        sb.append("]");
        return sb.toString();
    }

 Next, the number of reported physical education teacher requirements, such as the element that is reported according to the name of a classmate where their first of several (it corresponds to the array index), so this time we'll get a package indexing method specified element, as follows :

// Get the specified element index 
public  int GetIndex (Integer Element) {
         for ( int I = 0; I <elements.length -. 1; I ++ ) {
             IF (! Elements [I] .equals (Element)) {
                 Continue ; 
            } 
            return I; 
        } 
        the throw  new new a RuntimeException ( "not found" ); 
}

Then we try to get the students queued No. 4 position is as follows:

System.out.println ( "No. 4 position where students are:" + demo.GetIndex (4));

To here we have completed the basic requirements of the queue, but not enough, such as our custom initial capacity, here we designated as 5, after deletion, eventually there are four elements in the array, the array is added if we go down at least two or more elements, then print the array elements will throw an exception, so here we carry out automatic expansion of array to solve this problem, it is to add a method to transform when we need to determine whether the added element has exceeded the capacity of the array, If exceeded, we will expand the capacity of the array to 2 times the capacity of an existing array, then how should we judge it? We judged by the array size and capacity of the array, as follows: 

    public void Add(Integer element) {
        if (Size >= Elements.length) {
            Elements = Arrays.copyOf(Elements, 2 * Elements.length);
        }
        Elements[Size] = element;
        Size++;
    }
public  static  void main (String [] args) { 
        QueueDemo Demo = new new QueueDemo (. 5 ); 
        demo.Add ( . 1 ); 
        demo.Add ( 2 ); 
        demo.Add ( . 3 ); 
        demo.Add ( . 4 ); 
        Demo. the Add ( 5 ); 
        System.out.println (Demo); 
        // remove elements 
        demo.Remove (3 ); 
        System.out.println (Demo); 
        System.out.println ( "No. 4 position where students are:" demo.GetIndex + (. 4 )); 

        demo.Add ( . 6  );
        demo.Add (7);
        System.out.println(demo);
}

When we line up given the number 5, also said that the array initial capacity of 5, which is not flexible enough, if a physical education teacher has been clear that a few must stop, we will be able to receive signals directly specified physical education teacher, which like explicitly specify the initial capacity of the array, so that can guarantee will not throw an exception, but it will not affect when you add the element is inserted and expansion caused by the performance overhead, if it is not clear that a few stations, we can also default initial capacity, so the most flexible, everything changed and the best performance, as we define a default initial capacity and the transformation of queuing out the constructor, as follows:

    private int DEFAULT_CAPACITY = 10;

    public QueueDemo() {
        Elements = new Integer[DEFAULT_CAPACITY];
    }

    public QueueDemo(int capacity) {
        Elements = new Integer[capacity <= 0 ? DEFAULT_CAPACITY : capacity];
    }

Here we have yet to achieve the specified index position in the Insert method to insert elements, since you want to insert the specified index, first of all we have to check whether the specified index exceeds the size of the array, then elements of the specified index to move back one of the last remaining insert the specified index, as follows:

public void Insert(int index, Integer element) {
        if (Size <= index || index < 0) {
            throw new RuntimeException("超出数组边界");
        }
        System.arraycopy(Elements, index, Elements, index + 1,
                Size - index);
        System.out.println(this);
        Elements[index] = element;
        Size++;
 }
        Demo = QueueDemo new new QueueDemo (); 
        demo.Add ( . 1 ); 
        demo.Add ( 2 ); 
        demo.Add ( . 3 ); 
        demo.Add ( . 4 ); 
        demo.Add ( . 5 ); 
        System.out.println (Demo ); 
        // remove elements 
        demo.Remove (3 ); 
        System.out.println (Demo); 
        System.out.println ( "No. 4 position where the students is:" + demo.GetIndex (4 )); 

        demo.Add ( . 6 ); 
        demo.Add ( . 7 ); 
        System.out.println (Demo); 

        // insert elements
        demo.Insert(2, 20);
        System.out.println(demo);

As we first check whether the specified index is less than 0 or exceeds the size of the array, otherwise an exception is thrown, then we have here, making a copy Index + 1 elements from the specified index built by the methods provided, the length of the last element copied Size -Index. At this time, the specified index data is still 4, we specify the last value of the index is replaced by the position of our value to be inserted.

to sum up

As is our demand to achieve more complete line up, of course, some minor problems with the inspection parameters, see here must have a lot of children's shoes have been well aware of the fact that we achieved is a collection of Java, with the foundation of this lesson the next lesson we ArrayList source code analysis will be handy, thanks for reading, we see the next section.

Guess you like

Origin www.cnblogs.com/CreateMyself/p/11440876.html