我有一个方法可以将对象添加到数组中,但它会根据顺序添加它。所以我想说我有一个有苹果和可乐的数组。如果我想添加香蕉,它将介于这两个对象之间。但是当我运行jUnit测试时,我一直都会遇到错误。这是代码:
/**
* Adds an item to the list. This method assumes that the list is already
* sorted in alphabetical order based on the names of the items in the list.
*
* The new item will be inserted into the list in the appropriate place so
* that the list will remain alphabetized by names.
*
* In order to accomodate the new item, the internal array must be re-sized
* so that it is one unit larger than it was before the call to this method.
*
* @param itemToAdd refers to a Listable item to be added to this list
*/
public void add(Listable itemToAdd) {
int i;
Listable[] newItems = new Listable[items.length+1];
for(i=0; i<items.length;i++){
if(items[i].getName().compareTo(itemToAdd.getName()) < 0){
newItems[i] = items[i];
} else{
break;
}
}
int str=i;
for(i=str+1;i<items.length;i++){
newItems[i+1] = items[i];
}
newItems[str] = itemToAdd;
}
我一直收到错误消息,指出预期的测试结果为&lt; 14&gt;但得到&lt; 0&gt;所以现在我认为这意味着它的构造函数就是问题所在:
/**
* This constructor creates an empty list by creating an internal array
* of size 0. (Note that this is NOT the same thing as setting the internal
* instance variable to null.)
*/
public SortedListOfImmutables() {
int i = 0;
items = new Listable[0];
//orders the list
for( i=0;i<items.length;i++){
if(Food.FOOD_OBJECTS[i].getName().compareTo(Food.FOOD_OBJECTS[i+1].getName()) < 0){
items[i] = Food.FOOD_OBJECTS[i];
}else{
items[i+1] = Food.FOOD_OBJECTS[i];
}
}
}
答案 0 :(得分:0)
我认为至少你的一个问题是这个for循环:
for(i=str+1;i<items.length;i++){
newItems[i+1] = items[i];
}
我只是使用示例列表来说明原因。让我们说我们的项目列表包含{apple,banana,orange,pineapple}。然后我们要插入&#34; grape&#34;应插入&#34; banana&#34;和&#34;橙&#34;。第一个for循环在断开之前会做3次迭代(将#34; apple&#34;和#34; banana&#34;放入newItems,然后在i = 2时断开)你指定str = 2这是索引&# 34;葡萄&#34;应插入。但是当插入剩余的元素时,你设置i = str + 1,在这种情况下为3,所以
newItems[i+1] = items[i];
将菠萝&#34;菠萝&#34;到newItems的索引4,这是正确的但你完全跳过将索引2中的内容(&#34; orange&#34;)放到索引3的newItems中。 要解决此问题,您要么:
for(i=str;i<items.length;i++){
newItems[i+1] = items[i];
}
或:
for(i=str+1;i<items.length;i++){
newItems[i] = items[i-1];
}