public class OrderedArrayList<T extends Comparable<T>> {
/** This is an array of Objects of type T */
private T[] array;
private int numItems = 0;
private int itemsRemoved=0;
@SuppressWarnings("unchecked")
/**
* Construct an OrderedArrayList with 10 empty slots. Note the recipe for
* creating an array with the generic type. You'll want to reuse this
* recipe in the insert() method. You'll also possibly want to tweak this
* constructor a bit if you add other instance variables.
*/
public OrderedArrayList() {
array = (T[]) new Comparable[10];
}
@SuppressWarnings("unchecked")
/**
* _Part 1: Implement this method._
*
* Inserts a new item in the OrderedArrayList. This method should ensure
* that the list can hold the new item, and grow the backing array if
* necessary. If the backing array must grow to accommodate the new item, it
* should grow by a factor of 2. The new item should be placed in sorted
* order using insertion sort. Note that the new item should be placed
* *after* any other equivalent items that are already in the list.
*
* @return the index at which the item was placed.
*/
public int insert(T item) {
if (numItems==0){
array[0]=item;
numItems++;
return 0;
}
if (numItems==array.length){
T[] newArray = (T[]) new Comparable[array.length * 2];
for (int i = 0; i < array.length; i++){
newArray[i] = array[i];
}
array=newArray;
}
numItems++;
for (int j = numItems-1; j >= 0; j--) {
if (array[j].compareTo(item) <= 0){
array[j+1] = item;
return j+1;
}
else{
array[j+1] = array[j];
}
}
return -1;
}
삽입 Java에서 정렬, 두 번째 항목을 추가 할 수 없습니까?
@Test
public void removeWithTwoDifferentItems() {
int i;
OrderedArrayList<String> a = new OrderedArrayList<String>();
a.insert("Hello!");
a.insert("Zeno.");
i = a.find("Hello!");
assertEquals("Can't properly find the only string that should be in the list!", 0, i);
i = a.remove("Hel"+"lo!");
assertEquals("remove() expecting 1, but got something else", 1, i);
}
위는 시험이다 번째 항목에 추가하는 데 문제가 있다면이 과제에 대한 주어진 테스트를이 방법을이를 테스트하기 위해 노력하고있어, 그것은 오류가에있다 말할 때 Zeno를 삽입하십시오. 올바르게 작성한 것처럼 보이지만 해결 방법을 모르겠습니다. 또한 배열이 꽉 찼을 경우 배열은 20으로 증가 할 것으로 예상됩니다. 그게 잘못된 것인지는 잘 모르겠지만 주로 배열에 두 번째 것을 삽입하는 것에 대해 걱정하고 있습니다.
"삽입 Zeno에 오류가 있음을 알립니다." 내 영매 헬멧이 오늘 작동하지 않는 것 같습니다. 아마도 당신은 오류가 무엇인지 우리에게 말하면서 도울 수 있습니다. –
John3136
stacktrace에 오류 –
@RaviKumar를 제공 할 수 있습니까? xrex를 수행하는 방법을 알지 못합니다. 프로그래밍을 처음 접했습니다. – user3304219