definition of Backpack:
A backpack is a collection data type that does not support removing elements from it-the purpose of which is to help collect elements with columns and iterate through all the collected elements (columns can also check if the backpack is empty or get the number of elements in the backpack). The order of the iterations is indeterminate and irrelevant to the use case.
The implementation of the Backpack Java code:
Package com.learn.bag;
Import Java.util.Arrays;
Import Java.util.Iterator;
public class Bag<e> implements iterable<e> {
Private object[] table; The data structure inside the backpack container is an array of objects. Easy to accept any type (upward transformation)
private static final int default_size = 16;//default container size
private int size;//element number
Public Bag () {
Table=new Object[default_size];
}
adding elements
public void Add (E item) {
Ensurecapacity ();//container before adding
table[size++] = Item;
}
Container expansion Reference ArrayList the implementation of source code
private void Ensurecapacity () {
if (size >= table.length) {
int leg = table.length;
int Newcapacity=leg + (leg >> 1);//note to parentheses leg+ (leg>>1) There was no effect after the data was enlarged because there was no parentheses, causing the array to go out of bounds.
Table = arrays.copyof (table, newcapacity);
}
}
Determines whether an element is empty
public Boolean isEmpty () {
return size = = 0;
}
Get the number of elements
public int size () {
return size;
}
Public E get (int i) {
Assert i < 0 | | I >= size;
Return (E) table[i];
}
Because to implement the iterative function, in Java it is necessary to implement the Iterable interface, implement the iterator () method, return an iterative element (implements the iterator interface, Hasnext () method and Next () method, Java Syntax sugar knowledge)
@Override
Public iterator<e> Iterator () {
return new Itr ();
}
Private class Itr implements Iterator<e> {
private int cursor; Cursor to iterate up and down pointer movement
@Override
public Boolean hasnext () {
return cursor! = size ();
}
@Override
Public E Next () {
int i = cursor;
cursor++;
return get (i);
}
}
}
The realization of java-backpack