我正在尝试编写基于数组的线性列表,但使用 Java 泛型使列表能够存储任何值。通过这种方式,我可以创建使用它的其他程序,但传入不同的数据类型。我不完全确定如何做到这一点,任何帮助将不胜感激。
我想我正在努力尝试设置它并创建功能。泛型真的把我搞砸了。例如,尝试添加一个removeFirst()函数,我不能使用这样的循环:
for (int i = 0; i < n - 1; i++)
newList[i] = newList[i + 1];
— 正如它所说,表达式的类型必须是数组类型,但它解析为 ArrayList。
公平警告,我仍在学习数据结构。这是我到目前为止所拥有的:
import java.util.ArrayList;
public class LinearList<T> {
private static int SIZE = 10;
private int n = 0;
private final ArrayList<T> newList = new ArrayList<T>(SIZE);
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
public void add(T value, int position) {
newList.add(position, value);
n++;
}
public void addFirst(T value) {
newList.add(0, value);
n++;
}
public void removeLast() {
T value = null;
for (int i = 0; i < newList.size(); i++)
value = newList.get(i);
newList.remove(value);
n--;
}
public void removeFirst() {
newList.remove(0);
n--;
}
public T first() {
return newList.get(0);
}
public T last() {
int value = 0;
for (int i = 0; i < newList.size() - 1; i++)
value++;
return newList.get(value);
}
public int count() {
return n;
}
public boolean isFull() {
return (n >= SIZE);
}
public boolean isEmpty() {
return (n <= 0);
}
//part 4
public void Grow() {
int grow = SIZE / 2;
SIZE = SIZE + grow;
}
public void Shrink() {
int grow = SIZE / 2;
SIZE = SIZE - grow;
}
public String toString() {
String outStr = "" + newList;
return outStr;
}
}