Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorten array length once element is remove in Java

Tags:

java

arrays

Note: Following is my homework/assignment, feel free not to answer if you will.

I want to delete/remove an element from an String array(Set) basic, I'm not allowed to use Collections..etc.

Now I have this:

void remove(String newValue) {

            for ( int i = 0; i < setElements.length; i++) {
               if ( setElements[i] == newValue ) {
                    setElements[i] = "";

               }
            }

       }   

I does what I want as it remove the element from an array but it doesn't shorten the length. The following is the output, basically it remove the element indexed #1.

D:\javaprojects>java SetsDemo
Enter string element to be added
A
You entered A
Set size is: 5
Member elements on index: 0 A
Member elements on index: 1 b
Member elements on index: 2 hello
Member elements on index: 3 world
Member elements on index: 4 six
Set size is: 5
Member elements on index: 0 A
Member elements on index: 1
Member elements on index: 2 hello
Member elements on index: 3 world
Member elements on index: 4 six
like image 247
lupin Avatar asked May 06 '10 01:05

lupin


People also ask

Can you change size of array once created?

You can't change the size of an array in Java once the array is initialized.

Can you modify array length in Java?

The simple answer is that you cannot do this. Once an array has been created, its size cannot be changed. Instead, an array can only be "resized" by creating a new array with the appropriate size and copying the elements from the existing array to the new one.

How do you reduce the length of an array?

You cannot change the length of an array after you initialise it. What you can do is create another array with suitable size and make this large array eligible for Garbage Collector. Best is to use ArrayList if you are allowed to do that.


1 Answers

You can't change the length of an array object once it's created. Here's an excerpt from JLS 10.2. Array Variables:

Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.

This means that for this problem, you'd have to allocate a new array that's one-element shorter than the original array, and copy over the remaining elements.

If you need to remove element at index k, and the original array has L elements, then you need to copy over elements (upper bounds are exclusive):

  • From [0,k) to [0,k) (k elements)
  • From [k+1,L) to [k,L-1) (L-k-1 elements).
  • For a total of L-1 elements copied

static String[] removeAt(int k, String[] arr) {
    final int L = arr.length;
    String[] ret = new String[L - 1];
    System.arraycopy(arr, 0, ret, 0, k);
    System.arraycopy(arr, k + 1, ret, k, L - k - 1);
    return ret;
}
static void print(String[] arr) {
    System.out.println(Arrays.toString(arr));       
}   
public static void main(String[] args) {
    String[] arr = { "a", "b", "c", "d", "e" };
    print(arr); // prints "[a, b, c, d, e]"

    arr = removeAt(0, arr);
    print(arr); // prints "[b, c, d, e]"

    arr = removeAt(3, arr);
    print(arr); // prints "[b, c, d]"

    arr = removeAt(1, arr);
    print(arr); // prints "[b, d]"

    arr = removeAt(0, arr);
    arr = removeAt(0, arr);
    print(arr); // prints "[]"
}

This uses System.arraycopy; you can always write your own if this isn't allowed.

static void arraycopy(String[] src, int from, String[] dst, int to, int L) {
    for (int i = 0; i < L; i++) {
        dst[to + i] = src[from + i];
    }
}

This is a simplistic implementation that doesn't handle src == dst, but it's sufficient in this case.

See also

  • In java to remove an element in an array can you set it to null?
    • Answer: NO!

Note on == for String comparison

Most of the time, using == to compare String objects is a mistake. You should use equals instead.

String ha1 = new String("ha");
String ha2 = new String("ha");
System.out.println(ha1 == ha2); // prints "false"
System.out.println(ha1.equals(ha2)); // prints "true"

See also

  • Java String.equals versus ==
  • Difference Between Equals and ==
  • why equals() method when we have == operator?
like image 69
polygenelubricants Avatar answered Sep 29 '22 22:09

polygenelubricants