开发者

Removing null string from String Array

开发者 https://www.devze.com 2022-12-17 18:02 出处:网络
public static String[] removeString (String[] original) { String[] newString; List<String> list = new ArrayList<String>(Arrays.asList(original));
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'm trying to use the above code to remove the first string from an array of strings; however, it seems that al开发者_StackOverflow中文版though I do succeed in removing the first string from the array, I also made the last string in the array null. How can I make the array itself shorter?


Change your last-but-one line to:

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

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

As a sidenote: I'd advice that you revisit your naming conventions. According to the recommended naming conventions your method and variable names should start with a lower-case letter

Update: but you'd better use Arrays.copyOfRange(..) as suggested by others.


You will want to use the java.util.Arrays T[] copyOfRange(T[] original, int from, int to) method.

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


The problem is that, because your new array is smaller than the old one, the new array gets copied in the old one. The remaining fields are then filled with null. 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]);
 }

edit Or do what Bozho said, his code is better.

edit 2 Changes to accomodate comment below

0

精彩评论

暂无评论...
验证码 换一张
取 消