我正在尝试使用数组和泛型实现列表。我对如何将值插入通用列表感到困惑。 Scanner的nextXXX变体需要特定类型,但我们只在运行时知道类型。
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???
}
}
谢谢。
答案 0 :(得分:2)
这样的事情怎么样:
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);
}
}