2014-09-06 87 views
0

我想在阵列中的每个元素左移,如果有一个空值。 E.g如何使用循环移动数组中的每个元素?

public static void main(String[] args) { 
    String asd[] = new String[5]; 
    asd[0] = "zero"; 
    asd[1] = "one"; 
    asd[2] = null; 
    asd[3] = "three"; 
    asd[4] = "four; 

我所要的输出是

zero, one, three, four. 

长度也应调整

我怎样才能做到这一点使用循环?我尝试使用if语句来检查一个元素是否为空,并将该值复制到另一个数组中。但我不知道如何复制,如果有一个null。

回答

1

鉴于样的问题,我想你想要一个简单的,仅循环和数组只有基础的解决方案,以了解它是如何工作的。

你必须遍历数组,保持新的插入点的索引。最后,使用相同的索引,你可以“缩小”数组(实际上复制到一个新的更小的数组)。

String[] arr = {"a","b",null,"c",null,"d"}; 

// This will move all elements "up" when nulls are found 
int p = 0; 
for (int i = 0; i < arr.length; i++) { 
    if (arr[i] == null) continue; 
    arr[p] = arr[i]; 
    p++; 
} 

// This will copy to a new smaller array 
String[] newArr = new String[p]; 
System.arraycopy(arr,0,newArr,0,p); 

刚刚测试过这段代码。

编辑:

关于阵列收缩的可能性,而无需使用System.arraycopy,不幸的是在Java数组它们被实例化时的尺寸必须被声明,并且之后不能被改变(也没有取得较大也不小) 。

所以,如果你有长度为6的数组,并找到2个空,你有没有它缩小为4的长度,如果没有创建一个新的空数组,然后复制元素的方式。

列表可以扩展和收缩,并且更加得心应手。例如,与列表相同的代码将是:

String[] arr = {"a","b",null,"c",null,"d"}; 
List<String> list = new ArrayList<>(Arrays.asList(arr)); 
Iterator<String> iter = list.iterator(); 
while (iter.hasNext()) if (iter.next() == null) iter.remove(); 
System.out.println(list); 
+0

您好,感谢。虽然我想知道是否可以在for循环中使用system.arraycopy而不是使用system.arraycopy?除非你愿意,否则你不需要执行代码,但如果可能的话,你可以给我一个关于我应该怎么做的快速概念? – user2775042 2014-09-06 14:34:23

+0

编辑后解释为什么你需要System.arraycopy如何,而不是列出的工作。 – 2014-09-06 14:41:50

+0

感谢您的解释 – user2775042 2014-09-06 14:46:46

1

尝试:

int lengthNoNull = 0; 
for(String a : asd) { 
    if(a != null) { 
     lengthNoNull++; 
    } 
} 
String[] newAsd = new String[lengthNoNull]; 
int i = 0; 
for(String a : asd) { 
    if(a != null) { 
     newAsd[i++] = a; 
    } 
} 
0

的只使用阵列码片。

String[] x = {"1","2","3",null,"4","5","6",null,"7","8","9"}; 
    String[] a = new String[x.length]; 
    int i = 0; 
    for(String s : x) { 
     if(s != null) a[i++] = s; 
    } 
    String[] arr = Arrays.copyOf(a, i); 

或者这样:

String[] xx = {"1","2","3",null,"4","5","6",null,"7","8","9"}; 
    int pos = 0, i = 0; 
    String tmp; 
    for(String s : xx) { 
     if(s == null) { 
      tmp = xx[pos]; 
      xx[pos] = s; 
      xx[i] = tmp; 
      pos++; 
     } 
     i++; 
    } 
    String[] arr = Arrays.copyOfRange(xx, pos, xx.length); 
相关问题