我正在創建一個具有數組的類,並且我想實現方法add
,remove
和replace
。如何添加項目而不使用內置方法
但我不想使用任何內置的內部。
public class MySet {
public int set[];
private int size = 0;
public MySet(int size) {
this.set = new int[size];
}
public boolean add(int item) {
for (int i = 0; i < this.size(); i++) {
if (this.set[i] != 0) {
// add to array
}
}
this.size++;
return true;
}
public int size()
{
return this.size;
}
}
當您在Java中初始化一個固定大小的數組時,每個項目等於0
。具有if this.set[i] != 0
的部分是我堅持添加項目的地方。
我應該用指針的while循環嗎?如:
public boolean add(int item) {
int index = 0;
while (index <= this.size()) {
if (this.set[index] != 0 || index <=) {
// increase pointer
index++;
}
this.set[index] = item;
}
但是,如果我有一個數組如[7,2,0,1]在列表中,它不會得到在循環的最後一個項目,這是我需要的。
那麼,這通常如何完成?
你需要跟蹤你目前有多少物品。每次添加增加此值。每次刪除時,減少此值。 –
我推薦看看ArrayList是如何實現的,因爲這基本上就是你想要做的。您需要注意內部數組的增長和收縮,並確定何時需要更多空閒空間來重新分配它。 http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/util/ArrayList.java#ArrayList – nasukkin