开发者

How to create a List collection staring data in an array?

开发者 https://www.devze.com 2023-01-23 18:40 出处:网络
I was given a task to create an implementation of generic collection basing on simple array. Collection should implement List interface. Currently I have:

I was given a task to create an implementation of generic collection basing on simple array. Collection should implement List interface. Currently I have:

import java.util.*;
import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Iterator;

public class Main {
    public static void main(String[] args) {}
}

class MyCollection<T> implements List<T>{
    T[] tab;

    MyCollection() {
        this.tab = (T[])new Object[10];
    }

    public List subList(int from, int to){
        return new ArrayList();
    }

    public <T> T[] toArray(T[] t){}
    public T[] toArray()开发者_如何学Go{}
    public ListIterator listIterator(){}
    public ListIterator listIterator(int i){}
    public Iterator iterator(){}
    public boolean contains(){}
    public boolean contains(Object o){}
    public boolean isEmpty(){}
    public int size(){}
    public int lastIndexOf(Object o){}
    public int indexOf(Object o){}
    public T remove(int i){}
    public boolean remove(Object o){}
    public void clear(){}
    public void add(int i, T t){}
    public boolean add(T t){}
    public T set(int i, T t ){}
    public T get(int i){}
    public boolean retainAll(Collection c){}
    public boolean removeAll(Collection c){}
    public boolean addAll(int i, Collection c){}
    public boolean addAll(Collection c){}
    public boolean containsAll(Collection c){}
}

How can I implement the required methods if my data is stored in an array? How for example I can write listIterator for an array?


You may check out the java.util.ArrayList source code for some implementation patterns.


Start with the easy methods (e.g. get and set). Then move on to the harder ones and see if you can implement any of them in terms of the easier ones. If you get stuck, move on to a different method - it might give you some ideas about the one you're stuck on.

Iterators will probably be the trickiest, so maybe leave them until last. Hint: The iterators will probably need to be inner classes; to know where they are in the list; and have a reference back to the array.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号