3

Can I remove a specific element from array by mentioning index value? For example can I remove the character d by giving index value 1?

char[] words = { 'c', 'd', 'f', 'h', 'j' };
7
  • 1
    What do you mean by remove? Commented Nov 10, 2014 at 16:49
  • delete the character Commented Nov 10, 2014 at 16:49
  • 1
    Again, what does delete the character mean? Commented Nov 10, 2014 at 16:50
  • 2
    Here's the official tutorial on arrays. The first sentence has your answer. Commented Nov 10, 2014 at 16:53
  • 1
    Use an arraylist and its .remove() method. Arrays are immutable, so you cant 'remove' one, but rather create a new array of length -1 then populate it from the source. Commented Nov 10, 2014 at 16:53

6 Answers 6

1

Assuming you do not want your array to contain null values, then you would have to make a method that does it. Something like this should suffice:

public char[] remove(int index, char[] arr) {
    char[] newArr = new char[arr.length - 1];
    if(index < 0 || index > arr.length) {
        return arr;
    }
    int j = 0;
    for(int i = 0; i < arr.length; i++) {
        if(i == index) {
            i++;
        }
        newArr[j++] = arr[i];
    }

    return newArr;
}

Then just replace the old array with the result of remove().

Sign up to request clarification or add additional context in comments.

1 Comment

It throws an ArrayIndexOutOfBoundsException if the index is the last element. So, instead of i++, one should use continue.
1

If you don't want to use ArrayList, arraycopy is an alternative:

    System.arraycopy(words, 0, result, 0, i);
    System.arraycopy(words, i+1, result, i, result.length-i);

where i is your index to delete.

Hope I can help.

EDIT: Of course you should initially define the correct array lengths:

char[] result = new char[words.length-1];

1 Comment

btw, i/you should name it char[] word or char[] letters. also, your definition is wrong, it should be: char[] word = {'c','d','f','h','j'};
1

If you need to remove one or multiple elements from array without converting it to List nor creating additional array, you may do it in O(n) not dependent on count of items to remove.

Here, a is initial array, int... r are distinct ordered indices (positions) of elements to remove:

public int removeItems(Object[] a, int... r) {
    int shift = 0;                             
    for (int i = 0; i < a.length; i++) {       
        if (shift < r.length && i == r[shift])  // i-th item needs to be removed
            shift++;                            // increment `shift`
        else 
            a[i - shift] = a[i];                // move i-th item `shift` positions left
    }
    for (int i = a.length - shift; i < a.length; i++)
        a[i] = null;                            // replace remaining items by nulls

    return a.length - shift;                    // return new "length"
}  

Small testing:

Character[] words = {'c','d','f','h','j'};
removeItems(words, 1);
System.out.println(Arrays.asList(words));       // [c, f, h, j, null]

Comments

0

You can't remove an element from the array and "reduce" the array size. Once you have created an array, it's length is fixed.

You could change the value to something that has no meaning or is considered "empty", but you can't remove it.
Another option is to use a list, such as an ArrayList. It has a "remove" method that allows you to actually remove the element from it.

Comments

0
 import java.util.Arrays;
  public class Main
 {
 public static void main(String[] args) {
 int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};

 int removeIndex = 1;
 int j=0;
  for(int i = 0; i < my_array.length -1; i++)
  {

    if(i==1)
    {

    }
    else
     {
        my_array[j] = my_array[i];
        j++;
     }

    }
     System.out.println("Original Array : "+Arrays.toString(my_array));   
    }
  }

Comments

0

Using String class:

char[] words = { 'c', 'd', 'f', 'h', 'j' };
String str = new String(words);
words = (str.substring(0, Math.min(1, words.length)) + str.substring(Math.min(1 + 1, words.length))).toCharArray();

Running in jshell:

jshell> char[] words = { 'c', 'd', 'f', 'h', 'j' };
words ==> char[5] { 'c', 'd', 'f', 'h', 'j' }

jshell> String str = new String(words);
str ==> "cdfhj"

jshell> words = (str.substring(0, Math.min(1, words.length)) + str.substring(Math.min(1 + 1, words.length))).toCharArray();
words ==> char[4] { 'c', 'f', 'h', 'j' }

jshell>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.