Reputation: 95
I have the following array:
{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}
and I need to arrange it like this:
{x1, y1, z1, x2, y2, z2, x3, y3, z3}
Can you help me please? I have no idea how to start it.
Upvotes: 1
Views: 163
Reputation: 7556
Best way is to rely on ready made java methods as these are created and tested properly. Data type is although not clear from the array you specified,I am considering it as String
Code:-
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);
Upvotes: 0
Reputation: 2830
Previous answers are right, but if you need more quick copy, you can do something like the following. If your data contain chars, for exampleThis solution with work ONLY if the source array has 9*k elements i.e. 9, 18, 27,... etc. (as I understood your array is like that):
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];
}
Upvotes: 0
Reputation: 11132
Here is one way to do that:
Convert the array to a ArrayList
using Arrays
' asList
method.
Object[] objects = {new Object(), null, null, new Object(), null};
List<Object> tempList = new ArrayList(Arrays.asList(objects));
Loop through tempList
.
for(int i = 0; i < tempList.size(); i++)
{
remove()
the element from tempList
if it is null
.
if(tempList.get(i) == null)
{
tempList.remove(i);
i--;
}
}
Covert tempList
back to an array using ArrayList
's toArray()
method.
objects = tempList.toArray();
Here is a complete working example:
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();
}
}
Upvotes: 0
Reputation: 15675
I'm assuming by array you mean some sort of List
. If so, use an iterator, I'm assuming x1 is of class Integer:
Iterator<Integer> arrayIt = arrayIt.iterator();
while(arrayIt.hasNext()){
if(arrayIt.next() == null){
arrayIt.remove();
}
}
If your array is really large, it will run much faster if the array is implemented using a LinkedList
rather than, say, an ArrayList
Upvotes: 1