最近在学java,但是不太能理解java里的generic是如何实现的~求大神们指导一下~

解决方案 »

  1.   

    lz可以看看这个:http://yiminghe.iteye.com/blog/417325
      

  2.   

    看完这个例子你就明白泛型是怎么实现的
    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();
            }
        }
    }