Removing a null string from a String Array

public static String[] removeString (String[] original) { 
  String[] newString; 
  List<String> list = new ArrayList<String>(Arrays.asList(original)); 

  list.remove(0); 
  newString = list.toArray(original); 
  return newString; 
}

I am trying to use the above code to remove the first row from an array of strings; however it seems that although I was able to remove the first row from the array, I also made the last row in the null array. How can I make the array shorter?

+3
source share
3 answers

Change your last line to:

NewString = list.toArray(new String[list.size()]);

The method toArray(..)takes as an argument a list that it tries to populate with list data. You are passing a list of length 3, so the last item remains empty. With my suggestion, you create a new array with a new list size.

: .

: Arrays.copyOfRange(..), .

+4

java.util.Arrays T[] copyOfRange(T[] original, int from, int to) .

public static String[] RemoveString (String[] Original) { 
    return Arrays.copyOfRange(original, 1, original.length);
}
+4

The problem is that since your new array is smaller than the old, the new array is copied in the old. The remaining fields are filled with zero. This is ugly, but will solve your problem:

public static String[] RemoveString (String[] Original) { 
  List<String> list = new ArrayList<String>(Arrays.asList(Original)); 

  list.remove(0); 
  return list.toArray(new String[0]);
 }

change Or do what God said, his code is better.

edit 2 Changes to post a comment below

0
source

Source: https://habr.com/ru/post/1729727/


All Articles