1

:) 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? :)

Lawrence Wong
  • 1,129
  • 4
  • 24
  • 40
  • 3
    "I was told to just use an array", sounds like homework? – Jacob Jul 30 '11 at 15:12
  • possible duplicate of [Removing an element from an Array (Java)](http://stackoverflow.com/questions/642897/removing-an-element-from-an-array-java) – oluies Jul 30 '11 at 15:18
  • Possible duplicate of [How do I remove objects from an array in Java?](http://stackoverflow.com/questions/112503/how-do-i-remove-objects-from-an-array-in-java) – Brian Rogers Oct 13 '15 at 01:39

3 Answers3

0

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.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
0

You can simply set the value to something which is improbable (like -1 to save yourself the trouble of moving around and adjust arrays using System.arrayCopy or the likes. This of course assumes that the aim is to get the functionality working. If "moving" elements is an absolute requirement, you'd have to create a new array as mentioned by another comment here.

Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
0

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.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216