Placing null at the end of the List - java

I have a need to place null objects at the end of the List. Here is a sample what I have done for this purpose:
public static void main(String... args) {
List<String> strings = Arrays.asList(new String[]{"A", null, "B"});
for(String string : strings) {
System.out.println(string);
}
System.out.println("==================");
List<String> result = new ArrayList<String>();
List<String> nullStrings = new ArrayList<String>();
for(String string : strings) {
if(string != null) {
result.add(string);
} else {
nullStrings.add(string);
}
}
result.addAll(nullStrings);
for(String string : result) {
System.out.println(string);
}
}
I am looking forward to a more efficient and intelligent way to do this. Is it possible to swap inside the actual list so that null node get placed at the end, so that I don't need the other two list(nullStrings, result) and extra iteration.
Update
Sorting will not work for my case. This sample code I made just for testing purpose. Actually I have a different type of Object. Also Sorting will break the position.
Say I have this null, Obj2, Obj1, if do anything like sorting it may happens Obj1, Obj2, null. But I need Obj2, Obj1, null.

You can sort it using Collections.sort and a custom Comparator.
Here the compare code:
#Override
public int compare(String left, String right) {
if (left == right) {
return 0;
}
if (left == null) {
return 1;
}
if (right == null) {
return -1;
}
return 0;
}
Note that elements that have an equal value according to this Comparator won't be re-ordered. From Collections.sort:
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

Just move non-null elements to the front and fill the rest of the list with null.
int j = 0;
for (int i = 0; i < strings.size(); i++)
if (strings.get(i) != null){
strings.set(j, strings.get(i));
j++;
}
for (; j < strings.size(); j++)
strings.set(j, null);
If you are using LinkedList (or something not a RandomAccess), you'll need ListIterator
ListIterator<String> j = strings.listIterator();
for (ListIterator<String> i = strings.listIterator(); i.hasNext();) {
String s = i.next();
if (s != null) {
j.next();
j.set(s);
}
}
while (j.hasNext()) {
j.next();
j.set(null);
}

The general strategy looks fine to me. I would bring the following changes:
initialize the result list with the appropriate size
don't use a separate list for nulls. At the end of the iteration, you just need to compare the length of the initial list with the length of the result list to know how many nulls you need to add.
Although making a copy of the list will use more memory, it could well be faster than changing the initial list, because removing elements needs to move all the subsequent elements each time. And sorting is N*log(N), whereas copying elements is O(N).
[EDIT owlstead]
public static List<String> moveNullsToEnd(final List<String> strings) {
final List<String> newStrings = new ArrayList<String>(strings.size());
for (String string : strings) {
if (string != null) {
newStrings.add(string);
}
}
for (int i = 0, remaining = strings.size() - newStrings.size(); i < remaining; i++) {
newStrings.add(null);
}
return newStrings;
}

Below code you can use
Remove all the null elements
int noOfNull =0 ,i=0;
for(; i< strings.size() ; i++)
{
if(strings.get(i) == null)
{
noOfNull++;
}
}
strings.removeAll(Collections.singleton(null));
Filling the array with null after the not null elements
for(i =strings.size(); i < strings.size()+noOfNull ; i++)
{
strings.add(null);
}

List<String> list = new ArrayList<>();
list.add("BR64");
list.add("SWG620");
list.add("");
list.add("sw0");
list.add("R124");
list.add("R219");
list.add("TaGh20");
list.add("SW6505");
list.add("");
list.add(null);
list.add("SW_6505");
list.add("swd_157");
list.add("localhost");
list.add("qaGh20_241");
list.add("gen");
list.add(null);
list.add("taGh20");
list.add("zen");
list.add("QWG");
list.add("SWG62_");
list.add("SWG620");
Collections.sort(list, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
if (o1 != null && o2 != null && o1.length() > 0 && o2.length() > 0) {
return (Character.toLowerCase(o1.charAt(0)) == Character.toLowerCase(o2.charAt(0)))
? o1.compareTo(o2)
: (Character.toLowerCase(o1.charAt(0)) + o1.substring(1))
.compareTo((Character.toLowerCase(o2.charAt(0)) + o2.substring(1)));
} else {
return (o1 == o2) ? 0 : ((o1 == null || o1 == "") ? 1 : -1);
}
}
});
System.out.println(list);
Output-: [BR64, gen, localhost, QWG, qaGh20_241, R124, R219, SW6505, SWG620, SWG620, SWG62_, SW_6505, sw0, swd_157, TaGh20, taGh20, zen, , , null, null]

Related

Removing element from array. Getting null instead of actually removing element/index

I'm trying to remove an element from an array. I am running into an issue where when I run my program and remove a certain index. I get nulls in the place where the element/index should be removed entirely.
My output is when I execute list.display() in the main method is
Tom, Bob, Richard
However after I execute list.remove() and run the program. I get
null, null, Richard.
Any tips?
public class MyArrayList implements MyList {
private Object[] theList;
public MyArrayList()
{
theList = new Object[0];
}
public boolean add(Object toAdd){
if(toAdd != null) {
Object[] temp = new Object[theList.length + 1];
for(int i = 0; i < theList.length; i++) {
temp[i] = theList[i];
}
temp[theList.length] = toAdd;
theList = temp;
return true;
} else {
return false;
}
}
public Object remove(int index) {
if (index >= 0 && index < theList.length) {
Object[] temp = new Object[theList.length - 1];
theList[index] = null;
int j = 0;
for (int i = 0; i < theList.length; i++) {
if (i == index) {
continue;
}
temp[j++] = theList[i];
theList = temp;
}
return temp;
}
return null;
}
public class Main {
public static void main(String[] args) {
MyArrayList list = new MyArrayList();
list.add("Tom");
list.add("Bob");
list.add("Richard");
list.display();
list.remove(0);
list.remove(1);
list.display();
}
}
Where you call list.remove(0), you should be assigning the result back to list again. For example:
list = list.remove(0);
A couple of other things:
It's generally a bad idea to change the index variable within a loop. It's legal, but leads to logic errors that can be difficult to reason about and diagnose.
You're getting the null in your output because the remove method also mutates the theList when you execute:
theList[index] = null;
Since you're returning a copy of theList you don't need to also set that element of the theList array to null.
Since your code implements MyList which is not available in code, i could not run below sample on your code but you can have below logic in your code. You don't need extra temp array in remove method. Since it an array, you can start traversing array from index which has to be removed and start moving next element by one step before.
public Object remove(int index) {
if (theList == null || index < 0 || index >= theList.length) {
return theList;
}
for (int i = index; i < theList.length; i++) {
theList[i] = theList[i + 1];
}
return null;
}
You can trim array tail if it has more empty places based on some threshold.
the code is doing exactly what you asked it to do. Those removed values are null because you have this line
theList[index] = null;
Also think about what your intentions are.
list.remove(0); <- this will remove the first element so now list would be Rob, Richard
list.remove(1); <- this will remove the 2nd element of the modified list (Rob, Richard) so result would be Rob. This is probably not what you want.
instead of this
if (i == index) {
i++; // risk of out of bounds exception
}
you probably want this instead
if (i == index) {
continue;
}

How to check if the whole Array of a class is empty? [duplicate]

I have an int array which has no elements and I'm trying to check whether it's empty.
For example, why is the condition of the if-statement in the code below never true?
int[] k = new int[3];
if (k == null) {
System.out.println(k.length);
}
There's a key difference between a null array and an empty array. This is a test for null.
int arr[] = null;
if (arr == null) {
System.out.println("array is null");
}
"Empty" here has no official meaning. I'm choosing to define empty as having 0 elements:
arr = new int[0];
if (arr.length == 0) {
System.out.println("array is empty");
}
An alternative definition of "empty" is if all the elements are null:
Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
if (arr[i] != null) {
empty = false;
break;
}
}
or
Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
if (ob != null) {
empty = false;
break;
}
}
ArrayUtils.isNotEmpty(testArrayName) from the package org.apache.commons.lang3 ensures Array is not null or empty
Method to check array for null or empty also is present on org.apache.commons.lang:
import org.apache.commons.lang.ArrayUtils;
ArrayUtils.isEmpty(array);
Look at its length:
int[] i = ...;
if (i.length == 0) { } // no elements in the array
Though it's safer to check for null at the same time:
if (i == null || i.length == 0) { }
I am from .net background. However, java/c# are more/less same.
If you instantiate a non-primitive type (array in your case), it won't be null.
e.g. int[] numbers = new int[3];
In this case, the space is allocated & each of the element has a default value of 0.
It will be null, when you don't new it up.
e.g.
int[] numbers = null; // changed as per #Joachim's suggestion.
if (numbers == null)
{
System.out.println("yes, it is null. Please new it up");
}
In Java 8+ you achieve this with the help of streams allMatch method.
For primitive:
int[] k = new int[3];
Arrays.stream(k).allMatch(element -> element != 0)
For Object:
Objects[] k = new Objects[3];
Arrays.stream(k).allMatch(Objects::nonNull)
An int array is initialised with zero so it won't actually ever contain nulls. Only arrays of Object's will contain null initially.
The point here very simply is that the variable k isn't null because it points to the array. It doesn't matter that the array itself is empty. The null test in your post would only evaluate to true if the variable k didn't point to anything.
I tested as below. Hope it helps.
Integer[] integers1 = new Integer[10];
System.out.println(integers1.length); //it has length 10 but it is empty. It is not null array
for (Integer integer : integers1) {
System.out.println(integer); //prints all 0s
}
//But if I manually add 0 to any index, now even though array has all 0s elements
//still it is not empty
// integers1[2] = 0;
for (Integer integer : integers1) {
System.out.println(integer); //Still it prints all 0s but it is not empty
//but that manually added 0 is different
}
//Even we manually add 0, still we need to treat it as null. This is semantic logic.
Integer[] integers2 = new Integer[20];
integers2 = null; //array is nullified
// integers2[3] = null; //If I had int[] -- because it is priitive -- then I can't write this line.
if (integers2 == null) {
System.out.println("null Array");
}
if you are trying to check that in spring framework then isEmpty(Object[]) method in ObjectUtils class helps,
public static boolean isEmpty(#Nullable Object[] array) {
return (array == null || array.length == 0);
}
An int array without elements is not necessarily null. It will only be null if it hasn't been allocated yet. See this tutorial for more information about Java arrays.
You can test the array's length:
void foo(int[] data)
{
if(data.length == 0)
return;
}
public boolean empty() {
boolean isEmpty = true;
int i = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] != 0) {
i++;
}
}
if (i != 0) {
isEmpty = false;
}
return isEmpty;
}
This is as close as I got to checking if an int array is empty.
Although this will not work when the ints in the array are actually zero. It'll work for {1,2,3}, and it'll still return false if {2,0} but {0} will return true
I believe that what you want is
int[] k = new int[3];
if (k != null) { // Note, != and not == as above
System.out.println(k.length);
}
You newed it up so it was never going to be null.
You can also check whether there is any elements in the array by finding out its length, then put it into if-else statement to check whether it is null.
int[] k = new int[3];
if(k.length == 0)
{
//do something
}

String sorting null values

I have a string arraylist with some null values and some strings. I don't want to sort the arraylist but I should sort the arraylist such that null values comes last. Lets say arraylist is {1,2,null,6,5,null, 3}, I should get null values last {1,2,6,5,3,null,null}.
Solution , I currently have:
Right now, I am constructing new arraylist and If the value is null, I am not pushing it to new list otherwise I am adding it to new arraylist.
Any other better solution?
Thanks for the help.
If you are using Java 8, you can easily build the comparator you need:
Arrays.sort(stringArray, Comparator.nullsLast(Comparator.naturalOrder()));
But if you not using java 8 you can have a comparator like below
public class StringNullComparator implements Comparator<String> {
public int compare(String stringOne, String stringTwo) {
if (stringOne != null && stringTwo != null)
return stringOne.compareTo(stringTwo);
return (stringOne == stringTwo)?0:(stringOne==null? 1 : -1);
}
}
And you can use at stated below
Arrays.sort(stringArray, new StringNullComparator());
Custom Comparator to pass to sort:
public class StringComparator implements Comparator<String> {
public int compare(String s1, String s2) {
if (s1 != null && s2 != null)
return s1.compareTo(s2);
return (s1 == null) ? 1 : -1;
}
}
then:
Collectios.sort(list, new StringComparator());
If you want to avoid explicitly iterating over the whole list you could use ArrayList.indexOf() to find the null values, then remove() them. If you want to keep the values in the list you can then just add a null value to the end of the list. However I would imagine this approach is not great in terms of performance if this is a concern.
You can use NullComparator from apache.
Collections.sort(list, new NullComparator());
what about constructing new arraylist and If it a real value add it to the new list and if it is a null increment a counter.At last add the number of null equal to counter value.
If you want to sort null to the end and keep the order for the non-null elements this Comparator would do that :
class CompareStrings implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
if (o1 == null && o2 != null)
return 1;
if (o2 == null && o1 != null)
return -1;
return 0;
}
}
If both String are null or non-null they will compare equal. If only one is null it will compare as smaller than the non-null one.
How about:
class MyInteger implements Comparator<Integer> {
public int compare(Integer arg0, Integer arg1) {
if(arg1 == null) {
return -1;
}
return 0;
}
}
And we can use it like:
List<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(2);
al.add(null);
al.add(6);
al.add(5);
al.add(null);
al.add(3);
Collections.sort(al, new MyInteger());
All other solutions involve sorting. As you mentioned, you don't really need sorting. In case time complexity is a concern, you can use the following linear time solution (in-place):
public static <T> void nullsToEndInPlace(List<T> l) {
int i = 0;
int j = l.size() - 1;
while (i < j) {
T left = l.get(i);
T right = l.get(j);
if (left != null) {
i++;
} else if (right == null) {
j--;
} else {
l.set(i, right);
l.set(j, null);
i++;
j--;
}
}
}
Try this.
List<String> list = new ArrayList<>();
list.add("BR64");
list.add("SWG620");
list.add("");
list.add("sw0");
list.add("R124");
list.add("R219");
list.add("TaGh20");
list.add("SW6505");
list.add("");
list.add(null);
list.add("SW_6505");
list.add("swd_157");
list.add("localhost");
list.add("qaGh20_241");
list.add("gen");
list.add(null);
list.add("taGh20");
list.add("zen");
list.add("QWG");
list.add("SWG62_");
list.add("SWG620");
Collections.sort(list, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
if (o1 != null && o2 != null && o1.length() > 0 && o2.length() > 0) {
return (Character.toLowerCase(o1.charAt(0)) == Character.toLowerCase(o2.charAt(0)))
? o1.compareTo(o2)
: (Character.toLowerCase(o1.charAt(0)) + o1.substring(1))
.compareTo((Character.toLowerCase(o2.charAt(0)) + o2.substring(1)));
} else {
return (o1 == o2) ? 0 : ((o1 == null || o1 == "") ? 1 : -1);
}
}
});
System.out.println(list);
Output-:[BR64, gen, localhost, QWG, qaGh20_241, R124, R219, SW6505, SWG620, SWG620, SWG62_, SW_6505, sw0, swd_157, TaGh20, taGh20, zen, , , null, null]
Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.
For example, here’s a case-insensitive string comparison:
sorted("This is a test string from sohan".split(), key=str.lower)
['a', 'from', 'is', 'sohan', 'string', 'test', 'This']
here, key=str.lower() will convert every string to lower case and then sort the result.
For more info about sorting click here

Merging Lists using iterators

I need to merge two lists of strings in java and I'm not too sure on the best way to do it. I have to use iterators and the compareTo() method. For example...
Example: L1: A,B,C,D L2: B,D,F,G result: A,B,B,C,D,D,F,G
I can assume the input lists are already sorted and i cant use the contains() method. I have some initial checks but the while loop is what im stuck on.
public static ListADT<String> merge(ListADT<String> L1,ListADT<String> L2) throws BadListException {
ListADT<String> L3 = new ArrayList<String>;
if(L1 == null || L2 == null) {
throw new BadListException();
}
Iterator<String> itr1 = new L1.iterator();
Iterator<String> itr2 = new L2.iterator();
if(L1.size() == 0 && L2.size() == 0) {
return L3;
}
if(L1.size() == 0 && L2.size() != 0) {
for(int i = 0; i < L2.size(); i++) {
return L3.add(L2.get(i));
}
}
if(L2.size() == 0 && L1.size() != 0) {
for(int i = 0; i < L1.size(); i++) {
return L3.add(L1.get(i));
}
}
while(itr1.hasNext() || irt2.hasNext()) {
//merge the lists here?
}
}
Any help would be appreciated.
It's fairly straightforward if you just use variables to hold the current value from each iterator. This solution assumes your lists do not contain null, but it would not be difficult to add null-handling since the lists are sorted.
package com.example;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class IteratorMerge {
/**
* #param args
*/
public static void main(String[] args) {
List<String> list1 = Arrays.asList(new String[]{"A", "B", "C", "D"});
List<String> list2 = Arrays.asList(new String[]{"B", "D", "F", "G"});
System.out.println(merge(list1, list2));
}
public static List<String> merge(List<String> L1,List<String> L2) {
List<String> L3 = new ArrayList<String>();
Iterator<String> it1 = L1.iterator();
Iterator<String> it2 = L2.iterator();
String s1 = it1.hasNext() ? it1.next() : null;
String s2 = it2.hasNext() ? it2.next() : null;
while (s1 != null && s2 != null) {
if (s1.compareTo(s2) < 0) { // s1 comes before s2
L3.add(s1);
s1 = it1.hasNext() ? it1.next() : null;
}
else { // s1 and s2 are equal, or s2 comes before s1
L3.add(s2);
s2 = it2.hasNext() ? it2.next() : null;
}
}
// There is still at least one element from one of the lists which has not been added
if (s1 != null) {
L3.add(s1);
while (it1.hasNext()) {
L3.add(it1.next());
}
}
else if (s2 != null) {
L3.add(s2);
while (it2.hasNext()) {
L3.add(it2.next());
}
}
return L3;
}
}
Here's some pseudocode for the basic algorithm:
while(itr1 && itr2)
{
if(itr1 value < it2 value)
add itr1 to list
increment itr1
else
add itr2 to list
increment itr2
}
check if itr1 or itr2 still have more elements
while itr1 or itr2 has more elements, add those elements to the list
We know that the lists are sorted, so at each stage, we simply grab the smallest element from each list and add it to the merged list. If, at the end, one of the iterators is exhausted and the other is not, then we can simply iterate through the one which still has elements, appending each element in turn to the merged list.
As you've seen, doing this with Iterators in Java is a bit of a pain as next() removes the element. One way of getting around this is to utilize two Queues, one for each Iterator, that store the values from the call to next(). You then need to compare the head of each queue, adding the minimum to the merged list and then removing it from its respective Queue.
As you've found, it is sort of a pain to merge using iterators. Let's explicitly state why:
For each step of the merge, you want to inspect the first element of both sequences, but you only want to advance through one.
Iterator#next() bundles these inspect and advance operations into one operation, so it is impossible to inspect the head of both sequences without also advancing through both.
What you need is a way to peek at the first element in an Iterator without advancing it. If you had this ability, then the merge would look something like:
public <T extends Comparable<T>> List<T> merge(Iterator<T> it1, Iterator<T> it2) {
PeekableIterator<T> seq1 = new PeekableIterator<T>(it1);
PeekableIterator<T> seq2 = new PeekableIterator<T>(it2);
List<T> merged = new ArrayList<T>();
while (seq1.hasNext() && seq2.hasNext()) {
if (seq1.peekNext().compareTo(seq2.peekNext()) < 0) {
merged.add(seq1.next());
} else {
merged.add(seq2.next());
}
}
while (seq1.hasNext()) {
merged.add(seq1.next());
}
while (seq2.hasNext()) {
merged.add(seq2.next());
}
return merged;
}
And it turns out that it is not too difficult to create this PeekableIterator! You just need to keep track of whether or not you currently have a peeked element, and what that element is.
public class PeekableIterator<T> implements Iterator<T> {
private final Iterator<T> backing;
private boolean havePeek = false;
private T peek;
public PeekableIterator(Iterator<T> backing) {
this.backing = backing;
}
#Override
public boolean hasNext() {
return havePeek || backing.hasNext();
}
#Override
public T next() {
if (havePeek) {
havePeek = false;
return peek;
} else {
return backing.next();
}
}
public T peekNext() {
if (!havePeek) {
peek = backing.next();
havePeek = true;
}
return peek;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
EDIT
I didn't notice the comment above referring to the PeekingIterator in Google's Guava library, which is more or less the same as the PeekableIterator here. If you have access to third party libraries, this would certainly be preferable to rolling your own.
Don't try to manage merging of an empty list with a non empty one as a special case, just loop until at least one of the iterators is valid and do your work directly there:
public static ListADT<String> merge(ListADT<String> L1,ListADT<String> L2) throws BadListException {
ListADT<String> L3 = new ArrayList<String>;
Iterator<String> itr1 = new L1.iterator(), itr2 = new L2.iterator();
while (itr1.hasNext() || itr2.hasNext()) {
if (!itr1.hasNext())
L3.add(itr2.next());
else if (!itr2.hasNext())
L3.add(itr1.next());
else {
String s1 = peek from itr1
String s2 = peek from itr2;
if (s1.compareTo(s2) < 0) {
L3.add(itr1.next());
L3.add(itr2.next());
}
else {
L3.add(itr2.next());
L3.add(itr1.next())
}
}
}
}
public class MergeIterator {
public static void main(String[] args) {
List<String> s1 = new ArrayList<String>();
s1.add("a");
s1.add("z");
s1.add("b");
s1.add("k");
s1.add("c");
Collections.sort(s1);
List<String> s2 = new ArrayList<String>();
s2.add("p");
s2.add("a");
s2.add("d");
s2.add("n");
s2.add("m");
Collections.sort(s2);
Iterator<String> it1 = s1.iterator();
// sortIterator(it1);
Iterator<String> it2 = s2.iterator();
System.out.println();
combine(it1, it2);
}
private static Iterator<String> combine(Iterator<String> it1,
Iterator<String> it2) {
Iterator<String> it3 = null;
List<String> l1 = new ArrayList<>();
String s1 = null, s2 = null;
while (it1.hasNext() || it2.hasNext()) { //line 1
s1 = (s1 == null ? (it1.hasNext() ? it1.next() : null) : s1); //line 2
s2 = (s2 == null ? (it2.hasNext() ? it2.next() : null) : s2); // line 3
if (s1 != null && s1.compareTo(s2) < 0) { // line 4
l1.add(s1);
s1 = null;
} else {
l1.add(s2);
s2 = null;
}
}
it3 = l1.iterator();
return it3;
}
}

How can I check whether an array is null / empty?

I have an int array which has no elements and I'm trying to check whether it's empty.
For example, why is the condition of the if-statement in the code below never true?
int[] k = new int[3];
if (k == null) {
System.out.println(k.length);
}
There's a key difference between a null array and an empty array. This is a test for null.
int arr[] = null;
if (arr == null) {
System.out.println("array is null");
}
"Empty" here has no official meaning. I'm choosing to define empty as having 0 elements:
arr = new int[0];
if (arr.length == 0) {
System.out.println("array is empty");
}
An alternative definition of "empty" is if all the elements are null:
Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
if (arr[i] != null) {
empty = false;
break;
}
}
or
Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
if (ob != null) {
empty = false;
break;
}
}
ArrayUtils.isNotEmpty(testArrayName) from the package org.apache.commons.lang3 ensures Array is not null or empty
Method to check array for null or empty also is present on org.apache.commons.lang:
import org.apache.commons.lang.ArrayUtils;
ArrayUtils.isEmpty(array);
Look at its length:
int[] i = ...;
if (i.length == 0) { } // no elements in the array
Though it's safer to check for null at the same time:
if (i == null || i.length == 0) { }
I am from .net background. However, java/c# are more/less same.
If you instantiate a non-primitive type (array in your case), it won't be null.
e.g. int[] numbers = new int[3];
In this case, the space is allocated & each of the element has a default value of 0.
It will be null, when you don't new it up.
e.g.
int[] numbers = null; // changed as per #Joachim's suggestion.
if (numbers == null)
{
System.out.println("yes, it is null. Please new it up");
}
In Java 8+ you achieve this with the help of streams allMatch method.
For primitive:
int[] k = new int[3];
Arrays.stream(k).allMatch(element -> element != 0)
For Object:
Objects[] k = new Objects[3];
Arrays.stream(k).allMatch(Objects::nonNull)
An int array is initialised with zero so it won't actually ever contain nulls. Only arrays of Object's will contain null initially.
The point here very simply is that the variable k isn't null because it points to the array. It doesn't matter that the array itself is empty. The null test in your post would only evaluate to true if the variable k didn't point to anything.
I tested as below. Hope it helps.
Integer[] integers1 = new Integer[10];
System.out.println(integers1.length); //it has length 10 but it is empty. It is not null array
for (Integer integer : integers1) {
System.out.println(integer); //prints all 0s
}
//But if I manually add 0 to any index, now even though array has all 0s elements
//still it is not empty
// integers1[2] = 0;
for (Integer integer : integers1) {
System.out.println(integer); //Still it prints all 0s but it is not empty
//but that manually added 0 is different
}
//Even we manually add 0, still we need to treat it as null. This is semantic logic.
Integer[] integers2 = new Integer[20];
integers2 = null; //array is nullified
// integers2[3] = null; //If I had int[] -- because it is priitive -- then I can't write this line.
if (integers2 == null) {
System.out.println("null Array");
}
if you are trying to check that in spring framework then isEmpty(Object[]) method in ObjectUtils class helps,
public static boolean isEmpty(#Nullable Object[] array) {
return (array == null || array.length == 0);
}
An int array without elements is not necessarily null. It will only be null if it hasn't been allocated yet. See this tutorial for more information about Java arrays.
You can test the array's length:
void foo(int[] data)
{
if(data.length == 0)
return;
}
public boolean empty() {
boolean isEmpty = true;
int i = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] != 0) {
i++;
}
}
if (i != 0) {
isEmpty = false;
}
return isEmpty;
}
This is as close as I got to checking if an int array is empty.
Although this will not work when the ints in the array are actually zero. It'll work for {1,2,3}, and it'll still return false if {2,0} but {0} will return true
I believe that what you want is
int[] k = new int[3];
if (k != null) { // Note, != and not == as above
System.out.println(k.length);
}
You newed it up so it was never going to be null.
You can also check whether there is any elements in the array by finding out its length, then put it into if-else statement to check whether it is null.
int[] k = new int[3];
if(k.length == 0)
{
//do something
}

Categories