[英]How do you find the first element in array that has a certain characteristic?
[英]How do you remove the first instance of an element value in an array?
向 IntegerList 類添加一個 void removeFirst(int newVal) 方法,用於從列表中刪除第一次出現的值。 如果該值未出現在列表中,則不應執行任何操作(但這不是錯誤)。 刪除項目不應更改數組的大小,但請注意,數組值確實需要保持連續,因此當您刪除一個值時,您必須將其后的所有內容向下移動以填充其空間。 還要記住減少跟蹤元素數量的變量。
請幫忙,我已經嘗試了本網站上列出的所有其他關於“從數組中刪除元素”的解決方案,但都沒有奏效。
此方法支持與 Collection.remove() 相同的功能,這是 ArrayList 刪除第一個匹配元素的方式。
public boolean remove(int n) {
for (int i = 0; i < size; i++) {
if (array[i] != n) continue;
size--;
System.arraycopy(array, i + 1, array, i, size - i);
return true;
}
return false;
}
我建議您不要自己編寫此代碼,而建議您查看 Trove4J 的TIntArrayList
,它是int[]
的包裝器。您還可以閱讀 ArrayList 的代碼以了解它是如何編寫的。
使用下面的方法
public static <TypeOfObject> TypeOfObject[] removeFirst(TypeOfObject[] array, TypeOfObject valueToRemove) {
TypeOfObject[] result = Arrays.copyOf(array, array.length - 1);
List<TypeOfObject> tempList = new ArrayList<>();
tempList.addAll(Arrays.asList(array));
tempList.remove(valueToRemove);
return tempList.toArray(result);
}
您可以通過調用以下 JUnit 測試中演示的方法來刪除任何數組的第一個元素。
@Test
public void removeFirstTest() {
// Given
Integer valToRemove = 5;
Integer[] input = {1,2,3,valToRemove,4,valToRemove,6,7,8,9};
Integer[] expected = {1,2,3,4,valToRemove,6,7,8,9};
// When
Integer[] actual = removeFirst(input, valToRemove);
// Then
Assert.assertArrayEquals(expected, actual);
}
你可以這樣做:
int count; //No of elements in the array
for(i=0;i<count;i++)
{
if(Array[i]==element )
{
swap(Array,i,count);
if(count)
--count;
break;
}
}
int swap(int Array[],int i,int count)
{
int j;
for(j=i;j<=count-i;j++)
a[i]=a[i+1];
}
這不是完整的實現。您必須創建一個類並執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.