简体   繁体   中英

implementing list using arrays

I'm trying to implement list using arrays and generics. I'm stuck up on how to insert values into the generic list. Scanner's nextXXX variants expect a specific type but we know the type only at run time.

class Arraylist<T>
{
    static Scanner input = new Scanner(System.in);
    static T list[];
    static int top = -1;

    public static void displaymenu()
    {
        int choice;
        do {
            // get choice from user
            switch (choice) {
            case 1:
                list = createlist();
                break;
            case 2:
                insertnode();
                break;
            // ........
            }
        } while (true);
    }

    public static Object[] createlist()
    {
        list = new T[LIST_SIZE];
        return list;
    }

    public static void insertnode()
    {
        T o;
        top++;
        out.println("Enter the value to insert:");
        // o = user's input. I'm confused here???
    }
}

Thank you.

How about something like this:

public class ArrayList<T> {
    private T list[];
    private int last;
    public ArrayList() {
        list = (T[])new Object[10];
    }
    public void add(T elem) {
        if(last < list.length)
            list[last++] = elem;
        else {
            T newList[] = (T[])new Object[list.length*2];
            System.arraycopy(list, 0, newList, 0, list.length);
            list = newList;
            list[last++] = elem;
        }
    }
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for(int i = 0; i < last; i++) {
            sb.append(list[i].toString()+",");
        }
        sb.replace(sb.length()-1, sb.length(), "");
        sb.append(']');
        return sb.toString();
    }

    public static void main(String[] args) {
        ArrayList<String> stringList = new ArrayList<String>();
        stringList.add("Hello");
        stringList.add("World");
        stringList.add("Foo");
        System.out.println(stringList);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM