简体   繁体   中英

How do I remove objects from an Array in java based on certain condition?

:) I have

int[] code = new int[10];

It has the following values:

code[0] = 1234;
code[1] = 2222;
code[2] = 2121;
code[3] = 4321;
code[4] = 3333;
code[5] = 2356;

The code in this case refers to the serial number of the files. The user is suppose to enter the code of the file to remove that specific file.

Let's say user enter 3333 as the code to remove. code[4] = 3333 would be removed and code[5] = 2356 will move up to take its place. See below...

code[0] = 1234;
code[1] = 2222;
code[2] = 2121;
code[3] = 4321;
code[4] = 2356;

How would I tackle this problem?

I read up that using an Array List would make my life much easier. However, I was told to just use an array. Any help please? :)

That's simply not possible. Arrays have a fixed size, so you'll have to make a second array with its size reduced by 1 and copy all values except the one you want to keep. Or keep track of the "working size" of the array separately, at which point you're begun to reimplement ArrayList .

您可以简单地将值设置为不可能的值(例如-1 ,这样System.arrayCopy使用System.arrayCopy等之类的方法来移动和调整数组的麻烦。当然,这假定目标是使功能正常工作。如果“移动”元素是绝对要求,您必须创建一个新数组,如此处另一条评论所述。

How would I tackle this problem?

Allocate a new array and copy all of the values that you want to keep from the existing array to the new one.

You could also update the array in place, filling the "hole" at the end of the array with some special value that can't be a legal code.

Since this is a "sounds like homework" question, I'll leave you to figure out how to code it. (It is pretty simple. Just a loop, a test, and some careful manipulation of a second index.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM