当前位置: 首页 > >

java基础之自定义队列实现

发布时间:

package shujujiegou;

/**
* Created by lcc on 2017/6/21.
*/
public class DuiLie {
public static void main(String[] args) {
DuiLie lcc = new DuiLie();
lcc.add("shuangqi");
lcc.add("keai");
lcc.add("love");
lcc.add("xuyingming");
lcc.add("haojiuhaojiu");
System.out.println(lcc.Print());
System.out.println("----------");
DuiLie xuyingming = new DuiLie(3);
xuyingming.add("lcc");
xuyingming.add("lcc");
xuyingming.add("lcc");
int size = xuyingming.size();
xuyingming.remove();
int size1 = xuyingming.size();
xuyingming.clear();
int size2 = xuyingming.size();
System.out.println("shanchuqian " + size + " shanchuhou " + size1+ " clearhou " +size2);


}

private final int DEFAULT_SIZE = 10;
private Object elementData[];
private int front = 0;
private int rear = 0;
private int capactiy;

public DuiLie() {
capactiy = DEFAULT_SIZE;
elementData = new Object[capactiy];
}

public DuiLie(int initsize) {
this.capactiy = initsize;
elementData = new Object[capactiy];
}

public DuiLie(T element) {
this(); // 调用空的构造方法,相当于capactiy = DEFAULT_SIZE; elementData = new Object[capactiy];
elementData[front] = element;
front++;
}

public DuiLie(T element, int initsize) {
this(initsize);
elementData[front] = element;
front++;
}

public int size() {
return front - rear;
}

public boolean empty() {
return front == rear;
}

public void add(T element) {
if (rear > capactiy - 1) {
throw new IndexOutOfBoundsException("the duilie is full!");
}
elementData[rear++] = element;
}

public T remove() {
if (empty()) {
throw new IndexOutOfBoundsException("duilie is empty");
}
T oldElement = (T) elementData[front];
elementData[front] = null;
front++;
return oldElement;
}

public T element() {
if (empty()) {
throw new IndexOutOfBoundsException("duilie is empty");
}
return (T) elementData[front];
}

private void fill(Object[] a, Object val) {
for (int i = 0, len = a.length; i < len; i++)
a[i] = val;
}

public void clear() {
fill(elementData, null);
front = 0;
rear = 0;
}

public String Print() {
if (empty())
return "[]";
StringBuffer sb = new StringBuffer("[");
for (int i = front; i < rear; i++) {
sb.append(elementData[i] + ",");
}
int len = sb.length();
return sb.replace(len - 2, len, "]").toString();

}

}



友情链接: