安卓在Java中实现ArrayList。处理getUnique、addBefore和removeLast
public class MyArrayList<T> implements MyList<T>{
int num; //number of things in the list
T[] vals; //to store the contents
@SuppressWarnings("unchecked")
public MyArrayList() {
num = 0;
vals = (T[]) new Object[3];
}
public int size() { //returns number of things in the bag
return num;
}
public T get(int index) { //returns the indexth values
if((index < 0) || (index >= num))
throw new IndexOutOfBoundsException();
return vals[index];
}
@SuppressWarnings("unchecked")
public void add(T s) { //adds s to the list
if(num == vals.length) { //if array is full, make it bigger
T[] temp = (T[]) new Object[vals.length*2];
for(int i=0; i < num; i++)
temp[i] = vals[i];
vals = temp;
}
vals[num] = s;
num++;
}
public boolean contains(T s) { //returns whether s is list
for(int i=0; i < num; i++) { //ending condition should be num
if(vals[i].equals(s)) {
return true;
}
}
return false;
}
public T getUnique(){
T distinct = null;
int count = 0;
for (int i=0; i<vals.length; i++){
distinct = vals[i];
for (int j = 0; j<vals.length; j++){
if (vals[j] == vals[i]){
count++;
}
if (count == 1){
return distinct;
}
}
}
if (distinct == null){
throw new IllegalArgumentException();
}
return distinct;
}
public void addBefore(T input, T before){
for (int i = 0; i<vals.length; i++){
T temp = vals[i];
if(temp.equals(before)){
vals[i-1] = input;
}
}
}
public void removeLast(T s){
for (int i = vals.length; i>=0;i--){
if (vals[i].equals(s)){
vals[i] = vals[i+1];
}
}
}
}
我正在研究Java中的ArrayList实现。我无法完成getUnique、removeLast和addBefore方法。我似乎无法很好地处理数组,因为我似乎一直在替换值,而不是添加它。我做错了什么,请帮我一点忙
# 1 楼答案
在addBefore方法中,您使用新变量重写索引i-1上的内容,而不是添加它。您必须将列表的其余部分向右移动一个索引。同时尝试在第一个元素之前添加新的输入,它会崩溃
在removeLast中,您正在将倒数第二个变量移动到最后一个索引(倒数第二个=倒数第二个)。你应该在最后一个索引中调用remove
我假设您希望在getUnique方法中返回unique元素。你就快到了,看看第二个循环。顺便说一句,你不需要帮助变量来保存VAL[i],你可以直接返回VAL[i]