我有以下数组:
{x1, null, null, null, y1, null, null, null, z1, x2, null, null, null, y2, null, null, null, z2, x3, null, null, null, y3, null, null, null, z3}
我需要像这样安排:
{x1, y1, z1, x2, y2, z2, x3, y3, z3}
你能帮帮我吗?我不知道如何启动它。
答案 0 :(得分:5)
答案 1 :(得分:1)
我假设数组是指某种List
。如果是这样,使用迭代器,我假设x1是Integer类:
Iterator<Integer> arrayIt = arrayIt.iterator();
while(arrayIt.hasNext()){
if(arrayIt.next() == null){
arrayIt.remove();
}
}
如果您的数组非常大,如果使用LinkedList
而不是ArrayList
答案 2 :(得分:0)
以前的答案是正确的,但如果您需要更快速的副本,您可以执行以下操作。如果您的数据包含字符,例如,如果源数组有9 * k个元素,即9,18,27 ......等,则此工作 ONLY 的解决方案(正如我所知,您的数组就是这样) :
char[] source = {'1', ' ', ' ',
' ', '2', ' ',
' ', ' ', '3',
'4', ' ', ' ',
' ', '5', ' ',
' ', ' ', '6'};
char[] target = new char[source.length / 3];
int targetIndex = 0;
for (int i = 0; i < source.length; i += 9) {
target[targetIndex++] = source[i + 0];
target[targetIndex++] = source[i + 4];
target[targetIndex++] = source[i + 8];
}
答案 3 :(得分:0)
这是一种方法:
使用ArrayList
将数组转换为Arrays
' asList
method。
Object[] objects = {new Object(), null, null, new Object(), null};
List<Object> tempList = new ArrayList(Arrays.asList(objects));
循环浏览tempList
。
for(int i = 0; i < tempList.size(); i++)
{
remove()
来自tempList
的元素,如果它是null
。
if(tempList.get(i) == null)
{
tempList.remove(i);
i--;
}
}
使用ArrayList
's toArray()
method将tempList
隐藏回数组。
objects = tempList.toArray();
这是一个完整的工作示例:
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class RemoveArrayNull
{
public static void main(String[] args)
{
Object[] objects = new Object[] {new Object(), null, null, new Object(), null};
objects = removeNull(objects);
System.out.println(Arrays.toString(objects));
}
static Object[] removeNull(Object[] objects)
{
List<Object> tempList = new ArrayList(Arrays.asList(objects));
for(int i = 0; i < tempList.size(); i++)
{
if(tempList.get(i) == null)
{
tempList.remove(i);
i--;
}
}
return tempList.toArray();
}
}
答案 4 :(得分:0)
最好的方法是依赖现成的java方法,因为这些方法是正确创建和测试的。 数据类型虽然从您指定的数组中不清楚,但我将其视为String
代码: -
String []elements = new String[]{"x1", null, null, null, "y1", null, null, null, "z1", "x2", null, null, null, "y2", null, null, null, "z2", "x3", null, null, null, "y3", null, null, null, "z3"};
Set<String> set = new HashSet<String>(Arrays.asList(elements));
set.remove(null);