gpt4 book ai didi

java - 从数组中删除一个项目

转载 作者:行者123 更新时间:2023-11-29 09:24:01 24 4
gpt4 key购买 nike

class ArrayApp{

public static void main(final String[] args){
long[] arr; // reference to array
arr = new long[100]; // make array
int nElems = 0; // number of items
int j; // loop counter
long searchKey; // key of item to search for
// --------------------------------------------------------------
arr[0] = 77; // insert 10 items
arr[1] = 99;
arr[2] = 44;
arr[3] = 55;
arr[4] = 22;
arr[5] = 88;
arr[6] = 11;
arr[7] = 00;
arr[8] = 66;
arr[9] = 33;
nElems = 10; // now 10 items in array
// --------------------------------------------------------------
for(j = 0; j < nElems; j++){
System.out.print(arr[j] + " ");
}
System.out.println("");
// --------------------------------------------------------------
searchKey = 66; // find item with key 66
for(j = 0; j < nElems; j++){
if(arr[j] == searchKey){
break; // yes, exit before end
}
}
if(j == nElems){
System.out.println("Can’t find " + searchKey); // yes
} else{
System.out.println("Found " + searchKey); // no
}
// --------------------------------------------------------------
searchKey = 55; // delete item with key 55
for(j = 0; j < nElems; j++){
if(arr[j] == searchKey){
break;
}
}
for(int k = j; k < nElems - 1; k++){
arr[k] = arr[k + 1];
}
nElems--; // decrement size
// --------------------------------------------------------------
for(j = 0; j < nElems; j++){
System.out.print(arr[j] + " ");
}
System.out.println("");
} // end main()
} // end class ArrayApp
  • 为什么我们使用 j 和 nElems 来搜索一个数组。
  • 为什么我们再次将 j 分配给 k删除?我们不能从 j 中删除它吗本身?

最佳答案

nElemens 用于加快搜索速度。在上面的示例中,数组有 100 个字段。所以您需要搜索所有 100 个字段。但由于 nElemen(元素个数)只有 10,所以只需要搜索 10 个元素,而不是全部搜索 100 个。

但要小心:上面的算法假定数组以正确的顺序填充,并且具有值的字段之间不能有任何间隙。

然后将变量j作为循环变量访问数组中的不同字段。

例如

arr[5] 访问数组的 6. 字段。 arr[j] 访问 j。数组中的元素。有关 java 循环的基本信息:

http://leepoint.net/notes-java/flow/loops/loops.html

关于java - 从数组中删除一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4184696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com