Assume I have an array of strings like
String[] slot = new String[];
Won't compile as written; let's assume "new String[5]".
slot[0] = new String(first");
More uncompilable stuff. I'm just going to guess at what I
think you meant and talk about my guesses; if they don't match up
with your actual intent that's not my fault ...
I'll mention in passing that "new String(aString)" is almost
always silly, also wasteful.
slot[1] = new String(second");
slot[2] = new String(third");
slot[3] = new String(foo");
slot[4] = new String("bar");
Now I want to delete e.g. the third slot and shift all remaining slots 1 slot upwards.
The result should look like:
slot[0] = new String(first");
slot[1] = new String(second");
slot[2] = new String(foo");
slot[3] = new String("bar");
... and now the "[5]" returns to haunt you, because there's no
way to get rid of slot[4]. You can leave it still pointing to "bar"
or you can set it equal to null or you can point it to "Black Friday",
but slot[4] still exists and must have *some* kind of value.
If you really want slot[4] to disappear altogether, your only
recourse is to make a brand-new shorter array, copy the interesting
bits, and then jettison the entire old array and use the new one
in its place:
String[] newslot = new String[4];
newslot[0] = slot[0];
newslot[1] = slot[1];
newslot[2] = slot[3];
newslot[3] = slot[4];
slot = newslot; // out with the old, in with the new
How can I do this most easily?
It depends on what you want "this" to do with slot[4]. Your
basic alternatives are (1) shift the content of the existing array
around and maybe do something with slot[4], or (2) copy the good
bits into a brand-new array as I've shown.
Is this possible without iteration in a "while" loop?
Sure. You could do it with a for loop, or a do loop, or by
recursion, or by straight-line assignments, or with System.arrayCopy(),
or by Arrays.sort() with a really weird Comparator, or ...
If I, personally, were doing this, my first question would be "Is
this operation necessary?" And I'd ponder whether using an array, as
opposed to a List<String> (perhaps a LinkedList<String>) might let me
avoid the whole delete-and-slide thing to begin with. If I decided that
an array was actually required (for some reason not apparent in your
example), then I'd ask whether it was important to preserve the original
order among the survivors: Maybe "slot[2] = slot[4]; slot[4] = null;"
would suffice. If that, too, turned out to be a non-starter, I'd most
likely use System.arrayCopy() to slide the surviving tail downward.