求问generic是如何实现的?
最近在学java,但是不太能理解java里的generic是如何实现的~求大神们指导一下~ --------------------编程问答-------------------- lz可以看看这个:http://yiminghe.iteye.com/blog/417325 --------------------编程问答-------------------- 看完这个例子你就明白泛型是怎么实现的
package com.tur.demo;--------------------编程问答-------------------- 楼上的很详细了,楼主多看看,多自己写写,看不懂 记住会用就好了
import java.util.AbstractQueue;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class CircularArrayQueue<E> extends AbstractQueue<E> {
private E[] elements;
private int head;
private int tail;
private int count;
private int modCount;
public CircularArrayQueue(int capacity) {
elements = (E[]) new Object[capacity]; // 不能 new E[capacity]
head = 0;
tail = 0;
count = 0;
modCount = 0;
}
public boolean offer(E newElement) {
assert newElement != null;
if (count < elements.length) {
elements[tail] = newElement;
tail = (tail + 1) % elements.length;
count++;
modCount++;
return true;
} else {
return false;
}
}
public E poll() {
if (count == 0) return null;
E r = elements[head];
head = (head + 1) % elements.length;
count--;
modCount++;
return r;
}
public E peek() {
if (count == 0) return null;
return elements[head];
}
public int size() {
return count;
}
public Iterator<E> iterator() {
return new QueueIterator();
}
// 迭代器的实现
private class QueueIterator implements Iterator<E> {
private int modCountAtConstruction;
private int offset;
public QueueIterator() {
modCountAtConstruction = modCount;
offset = 0;
}
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
E e = elements[(head + offset) % elements.length];
offset++;
return e;
}
public boolean hasNext() {
if (modCountAtConstruction != modCount) {
throw new ConcurrentModificationException();
}
return offset < count;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
补充:Java , Java SE