您的位置:首页 > 编程语言 > Java开发

java 实现泛型List接口

2014-08-16 22:04 253 查看
import java.util.Collection;

import java.util.Iterator;

import java.util.List;

import java.util.ListIterator;

import java.util.RandomAccess;

public class MyList<T> implements List<T>, RandomAccess, Cloneable, java.io.Serializable  {

/**

*/
private static final long serialVersionUID = 1L;
private T[]     objs;       // 数组容器对象

    private final int    BUF   = 16; // 数组初始长度,默认为16

    private final double EXT   = 2;  // 如果不够,默认增加的长度为原数组的2倍

    private final double PER   = 0.5; // 空白处大于这个百分比就缩短长度

    private int          count = 0;  // 实际的长度(去掉尾部NULL元素)

    /**

     * 建立一个初始长度为10的容器

     */

    @SuppressWarnings("unchecked")
public MyList(){

        objs = (T[]) new Object[BUF];

    }

    private MyList(T[] obj){

        objs = obj.clone();

    }

    

    /**

     * 返回实际集合长度

     */
@Override
public int size() {
return count;
}

    /**

     * 集合是否为空(长度是否为0)

     */
@Override
public boolean isEmpty() {
return count == 0;
}

    /**

     * 如果列表包含指定的元素,则返回 true

     */
@Override
public boolean contains(Object o) {

        for (Object obj : objs) {

            if (o.equals(obj)) return true;

        }

        return false;
}

    /**

     * 返回此集合的迭代器

     */
@Override
public Iterator<T> iterator() {
return new Itr();
}

    /**

     * 返回数组

     */
@Override
public T[] toArray() {
return newArray();
}

    /**

     * 返回按适当顺序(从第一个元素到最后一个元素) 包含列表中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。

     */
@SuppressWarnings({ "hiding", "unchecked" })
@Override
public <T> T[] toArray(T[] a) {

        if (a.length <= count) {

            return (T[]) newArray();

        } else {

            T[] obj = (T[]) newArray();

            for (int i = 0; i < a.length; i++) {

                if (i <= obj.length) a[i] = obj[i];

                else a[i] = null;

            }

            return obj;

        }
}

    /**

     * 添加元素到尾部

     */
@Override
public boolean add(T e) {

        if (e == null) throw new NullPointerException("指定的对象为空");

        extSize();

        objs[count] = e;

        count++;

        return true;
}

    /**

     * 移除指定的第一个出现的元素

     */
@Override
public boolean remove(Object o) {

        if (o == null) throw new NullPointerException("指定的对象为null");

        return delete(o);
}

    /**

     * 如果列表包含指定 collection 的所有元素,则返回 true。

     */

    @SuppressWarnings({"unchecked", "rawtypes" })

    @Override
public boolean containsAll(Collection<?> c) {

        T[] objsclone = objs.clone();

        for (Iterator it = c.iterator(); it.hasNext();) {

            boolean flag = false;

            T o = (T) it.next();

            if (o == null) throw new NullPointerException("指定的对象有空元素");

            for (int i = 0; i < objsclone.length; i++) {

                if (o.equals(objsclone[i])) {

                    objsclone[i] = null;

                    flag = true;

                    break;

                }

            }

            if (!flag) return false;

        }

        return true;
}

    

    /**

     * 合并指定集合到尾部

     */

    @SuppressWarnings({"unchecked", "rawtypes" })

    @Override
public boolean addAll(Collection<? extends T> c) {

        if (c.size() == 0) return false;

        changeArray(count + c.size() + BUF);

        int x = count - 1;

        for (Iterator it = c.iterator(); it.hasNext(); x++) {

            objs[x] = (T) it.next();

            count++;

        }

        return true;
}

    /**

     * 添加一组元素到指定位置

     */

    @SuppressWarnings({"unchecked", "rawtypes" })
@Override
public boolean addAll(int index, Collection<? extends T> c) {

        if (index < 0) throw new IndexOutOfBoundsException("角标不能小于零");

        else if (index > objs.length - 1) throw new IndexOutOfBoundsException("角标超出范围");

        move(index, c.size());

        if (objs[index] != null) throw new NullPointerException("原位置不为空");

        Iterator it = c.iterator();

        for (int i = index; it.hasNext(); i++) {

            objs[i] = (T) it.next();

        }

        return true;
}

    /**

     * 删除含有指定列表的元素

     */
@Override
public boolean removeAll(Collection<?> c) {

        for (Object o : c) {

            if (!delete(o)) throw new NullPointerException("此列表包含了一个空元素");

        }

        return true;
}

    /**

     * 仅在列表中保留指定 collection 中所包含的元素,取交集

     */

    @SuppressWarnings({"unchecked" })
@Override
public boolean retainAll(Collection<?> c) {

        int len = count < c.size() ? count : c.size();

        T[] objsclone = (T[]) new Object[len];

        int x = 0;

        for (Iterator<T> it = (Iterator<T>) c.iterator(); it.hasNext();) {

            for (int i = 0; i < count; i++) {

                Object o = it.next();

                if (o == null) continue;

                if (o.equals(objs[i])) {

                    objsclone[x] = objs[i];

                    objs[i] = null;

                    x++;

                }

            }

        }

        objs = objsclone;

        count = x;

        return true;
}

    /**

     * 清空集合

     */
@SuppressWarnings("unchecked")
@Override
public void clear() {

        if (objs.length == BUF && count == 0) return;

        objs = (T[]) new Object[BUF];

        count = 0;
}

    /**

     * 获取指定下标的元素

     */
@Override
public T get(int index) {

        if (index < 0) throw new IndexOutOfBoundsException("下标不能小于零");

        else if (index > objs.length - 1) throw new IndexOutOfBoundsException("下标超出范围");

        return objs[index];
}

    /**

     * 设置指定下标的值,返回以前的的值

     */
@Override
public T set(int index, T element) {

        if (element == null) throw new NullPointerException("指定的对象为空");

        else if (index < 0) throw new IndexOutOfBoundsException("下标不能小于零");

        else if (index > objs.length - 1) throw new IndexOutOfBoundsException("下标超出范围");

        T old = objs[index];

        objs[index] = element;

        return old;
}

    /**

     * 添加元素到指定位置

     */
@Override
public void add(int index, T element) {

        if (element == null) throw new NullPointerException("指定的对象为空");

        move(index, 1);

        if (objs[index] != null) throw new NullPointerException("原位置不为空");

        objs[index] = element;

        count++;
}

    /**

     * 移除指定下标元素,返回移除的值

     */
@Override
public T remove(int index) {

        if (index < 0) throw new IndexOutOfBoundsException("角标不能小于零");

        else if (index > objs.length - 1) throw new IndexOutOfBoundsException("角标超出范围");

        T old =  delete(index);

        return old;
}

    /**

     * 返回此列表中第一次出现的指定元素的索引;如果此列表不包含该元素,则返回 -1。

     */
@Override
public int indexOf(Object o) {

        if (o == null) throw new NullPointerException("指定的对象为空");

        for (int i = 0; i < objs.length; i++) {

            if (objs[i].equals(o)) return i;

        }

        return -1;
}

    /**

     * 返回此列表中最后出现的指定元素的索引;如果列表不包含此元素,则返回 -1。

     */
@Override
public int lastIndexOf(Object o) {

        if (o == null) throw new NullPointerException("指定的对象为空");

        for (int i = objs.length - 1; i <= 0; i--) {

            if (objs[i].equals(o)) return i;

        }

        return -1;
}

    /**

     * 返回此集合的ListIterator迭代器

     */
@Override
public ListIterator<T> listIterator() {
return new listItr();
}

    /**

     * 返回一个ListIterator迭代器,初始位置在index

     */
@Override
public ListIterator<T> listIterator(int index) {
return new listItr(index);
}

    /**

     * 返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之间的部分视图。

     */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public List<T> subList(int fromIndex, int toIndex) {

        if (fromIndex > toIndex) return null;

        else if (count == 0) return null;

        else if (fromIndex < 0) return null;

        T[] arr = (T[]) new Object[toIndex - fromIndex + 1];

        int x = 0;

        for (int i = 0; i < count; i++) {

            if (i >= fromIndex && i < toIndex) {

                arr[x++] = objs[i];

            }

        }

        return new MyList(arr);
}

    /**

     * 返回指定格式文本 [element1,element2,...]

     */

    @Override

    public String toString() {

        String str = "[";

        for (int i = 0; i < count; i++) {

            if (i == count - 1) str += objs[i];

            else str += objs[i] + ",";

        }

        str += "]";

        return str;

    }

    // Iterator迭代器

    private class Itr implements Iterator<T> {

        private int cor = -1; // 指针位置

        // 是否有下一个

        @Override

        public boolean hasNext() {

            int index = cor + 1;

            if (index < 0 || index >= count) return false;

            return true;

        }

        // 下一个

        @Override

        public T next() {

            if (!hasNext()) return null;

            return objs[++cor];

        }

        // 删除

        @Override

        public void remove() {

            delete(cor);

        }

    }

    // ListIterator迭代器

    private class listItr implements ListIterator<T> {

        private int cor; // 指针位置

        listItr(){

            cor = -1;

        }

        listItr(int index){

            cor = index - 1;

        }

        // 是否有下个元素

        @Override

        public boolean hasNext() {

            int index = cor + 1;

            if (index < 0 || index >= count) return false;

            return true;

        }

        // 返回列表中的下一个元素。

        @Override

        public T next() {

            if (!hasNext()) return null;

            return objs[++cor];

        }

        // 前面是否有元素

        @Override

        public boolean hasPrevious() {

            int index = cor - 1;

            if (index < 0 || index >= count) return false;

            return true;

        }

        // 返回列表中的前一个元素。

        @Override

        public T previous() {

            if (!hasPrevious()) return null;

            return objs[--cor];

        }

        // 获取前面一个元素的位置

        @Override

        public int nextIndex() {

            return cor + 1;

        }

        // 获取后面一个元素的位置

        @Override

        public int previousIndex() {

            return cor;

        }

        // 删除迭代处的元素

        @Override

        public void remove() {

            delete(cor);

        }

        // 设置迭代处位置新的值

        @Override

        public void set(T e) {

            if (e == null) throw new NullPointerException("指定的对象为空");

            objs[cor] = e;

        }

        // 添加到尾部

        @Override

        public void add(T e) {

            if (e == null) throw new NullPointerException("指定的对象为空");

            extSize();

            objs[count] = e;

            count++;

        }

    }

    private T delete(int index) {

        // 删除指定位置的元素,后面的往前移动

        T old = objs[index];

        if (index == count - 1) {

            objs[index] = null;

            count--;// 实际长度减少1

            removeNull();

            return old;

        }

        for (; index < count - 1; index++) {

            objs[index] = objs[index + 1];

        }

        objs[count - 1] = null;

        count--;// 实际长度减少1

        removeNull();

        return old;

    }

    private boolean delete(Object o) {

        // 删除指定的找到的第一个元素,后面的往前移动

        if (o == null) return false;

        for (int i = 0; i < objs.length - 1; i++) {

            if (o.equals(objs[i])) {

                return delete(i) != null;

            }

        }

        return false;

    }

    private void move(int index, int length) {

        // 从指定位置往后移动

        changeArray(objs.length + length);

        for (int i = count - 1; i >= index; i--) {

            objs[i + length] = objs[i];

            objs[i] = null;

        }

    }

    private void extSize() {

        // 数组长度扩充

        if (objs.length == count) changeArray((int) (count * EXT) + BUF + count);

    }

    @SuppressWarnings("unchecked")
private void changeArray(int length) {

        // 改变数组,(加长或缩短)

        T[] ar = (T[]) new Object[length];

        for (int i = 0; i < count; i++) {

            ar[i] = objs[i];

        }

        objs = ar;

    }

    private void removeNull() {

        // 缩小长度

        if ((double) count / objs.length < PER) changeArray(count + BUF);

    }

    @SuppressWarnings("unchecked")
private T[] newArray() {

        // /复制一个数组,返回有效长度

        if (objs.length == count) return objs.clone();

        T[] o = (T[]) new Object[count];

        for (int i = 0; i < count; i++) {

            o[i] = objs[i];

        }

        return o;

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  泛型 java List