Как найти null в массиве

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);
}

Lii's user avatar

Lii

11.4k8 gold badges63 silver badges88 bronze badges

asked Mar 3, 2010 at 9:20

Ankit Sachan's user avatar

Ankit SachanAnkit Sachan

7,66015 gold badges63 silver badges98 bronze badges

3

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;
  }
}

Miles's user avatar

Miles

31.1k7 gold badges62 silver badges74 bronze badges

answered Mar 3, 2010 at 9:22

cletus's user avatar

4

ArrayUtils.isNotEmpty(testArrayName) from the package org.apache.commons.lang3 ensures Array is not null or empty

Misa Lazovic's user avatar

Misa Lazovic

2,8159 gold badges31 silver badges38 bronze badges

answered Sep 3, 2015 at 19:18

Shravan Ramamurthy's user avatar

0

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);

answered Jul 16, 2019 at 13:56

Jackkobec's user avatar

JackkobecJackkobec

5,70934 silver badges33 bronze badges

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) { }

answered Mar 3, 2010 at 9:23

Mike's user avatar

MikeMike

2,4071 gold badge24 silver badges32 bronze badges

1

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");
}

answered Mar 3, 2010 at 9:23

shahkalpesh's user avatar

shahkalpeshshahkalpesh

33.1k3 gold badges63 silver badges88 bronze badges

2

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)

answered Apr 21, 2020 at 21:18

Shivang Agarwal's user avatar

Shivang AgarwalShivang Agarwal

1,8051 gold badge14 silver badges19 bronze badges

An int array is initialised with zero so it won’t actually ever contain nulls. Only arrays of Object’s will contain null initially.

answered Mar 3, 2010 at 9:26

objects's user avatar

objectsobjects

8,6374 gold badges29 silver badges38 bronze badges

3

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);
    }

Datz's user avatar

Datz

3,0063 gold badges21 silver badges47 bronze badges

answered Nov 30, 2020 at 13:11

saravana kumar ramasamy's user avatar

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.

answered Jan 12, 2016 at 16:45

hubbabubba's user avatar

hubbabubbahubbabubba

8971 gold badge8 silver badges17 bronze badges

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");
        }   

answered Sep 19, 2017 at 3:25

Uddhav P. Gautam's user avatar

Uddhav P. GautamUddhav P. Gautam

7,2233 gold badges46 silver badges64 bronze badges

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;
}

answered Mar 3, 2010 at 9:22

unwind's user avatar

unwindunwind

390k64 gold badges468 silver badges604 bronze badges

    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

answered Apr 27, 2018 at 3:35

nanatash's user avatar

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.

answered Mar 4, 2010 at 17:55

vickirk's user avatar

vickirkvickirk

3,9672 gold badges22 silver badges37 bronze badges

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
}

answered Nov 14, 2017 at 5:05

J_fruitty's user avatar

J_fruittyJ_fruitty

471 gold badge1 silver badge6 bronze badges

At first I was thinking,
«They need to use pointer arithmetic so the
object doesn’t get auto de-referenced by the
«[ ]» operator.

Then I realized, no… Arrays in C don’t have
null slots
.

I conclude, the asker is:

  1. Using an array of structs.

  2. Using it as if it were an array of
    pointers to structs.

peoro’s solution is pretty good. But I would recommend modifying it a bit.
Add a «.exists» property to your struct if you want to do it the lazy/simple way.
Simple is not a bad thing, the more parts in a machine the more things that can go wrong.

Code below demonstrates two things:

  1. Faking a sparse array using peoro’s solution with .exists flag modification.

  2. An actual sparse array using double pointers.


#include<stdlib.h> //:for: malloc(...)
#include<stdlib.h> //:for:   free(...)
#include <stdio.h> //:for: printf(...)
int main( void ){
    printf("[BEG:main]n");

    typedef struct MyStruct{
        int whatever;
    } MyStruct;

    int        num = 16; //:sixteen_elements

    //:USE CALLOC HERE! If you use malloc you'll
    //:end up with something even worse than
    //:null pointers... Pointers that point to
    //:random places in memory. 
    //:
    //: It will make your:
    //: if( arr[i] != NULL )... 
    //: look before you leap check worthless.
    MyStruct** arr =(
        calloc(
            1 //:allocating 1 item: arr

            //:Amount of memory taken up by
            //:all 16 MyStruct pointers in array.
        ,   sizeof(MyStruct*)*num
        )
    );;

    //:Initialize only the EVEN slots:
    for(int i = 0; i < num; i+=2 ){
        //:Create new MyStruct in slot i,
        //:initialized with junk data.
        arr[i]= malloc(sizeof(MyStruct));
    };;

    //:If element not null, set it's whatever:
    for(int i = 0; i < num; i++){
        if(NULL != arr[i]){
            arr[i] -> whatever = i;
        };;
    };;

    //:Loop and print to confirm:
    for(int i = 0; i < num; i++){
        if(NULL != arr[i]){
            printf("whatever: %dn", arr[i] -> whatever);
        };;
    };;

    //:ALTERNATIVELY:
    //:If we were going to use peoro's method,
    //:I would advise adding a ".exists" flag
    //:to your struct.

    typedef struct DoublePointersAreTooMuchWork{
        int exists;

        //:Because we are going to use malloc this
        //:time, we have no guarantee what this
        //:value will be. but you will probably
        //:see all of them == 0. If you set
        //: num=1000 you'll probably see a non-zero
        //: entry somewhere. But, no guarantees!
        int mystery_value;
    } MyStruct02;

    MyStruct02* arr2 = malloc(sizeof(MyStruct02)*num);
    for(int i = 0; i < num; i++ ){

        if( i%2 ){ //:evens
            arr2[i].exists = 1;
        }else{
            arr2[i].exists = 0;
        };;
    };;

    for(int i = 0; i < num; i++ ){
        if( arr2[i].exists ){
            printf("Exists:val:%dn", arr2[i].mystery_value);
        }else{
            printf("[Pretend_I_Dont_Exist]n");
        };
    }

    printf("[END:main]n");
} //[[main]____________________________________]//

/** ****************************************** ***
OUTPUT:
[BEG:main]
whatever: 0
whatever: 2
whatever: 4
whatever: 6
whatever: 8
whatever: 10
whatever: 12
whatever: 14
[Pretend_I_Dont_Exist]
Exists:val:0
[Pretend_I_Dont_Exist]
Exists:val:0
[Pretend_I_Dont_Exist]
Exists:val:0
[Pretend_I_Dont_Exist]
Exists:val:0
[Pretend_I_Dont_Exist]
Exists:val:0
[Pretend_I_Dont_Exist]
Exists:val:0
[Pretend_I_Dont_Exist]
Exists:val:0
[Pretend_I_Dont_Exist]
Exists:val:0
[END:main]
*** ****************************************** **/

While I am at it. If you want to run from the command line, name the file:
«NAE.C99», then create a bash file called «NAE.SH» and put this into it.
Double click the script to run it, or use «./NAE.SH» where it resides in your
git bash terminal.

##################################################
############################# SC[ hkmf-strict ] ##
##################################################
base_name_no_extension="NAE"
##################################################
MY_COMMAND_STRING=$(cat << GCC_COMMAND_01
    gcc                                     
    -x c                                    
    -c $base_name_no_extension.C99          
    -o my_object_file.o                     
    -m64                                    
GCC_COMMAND_01
)                                       
C=$MY_COMMAND_STRING  ############################
C=$C"-Werror        " ## WarningsAreErrors      ##
C=$C"-Wfatal-errors " ## StopAtFirstError       ##
C=$C"-Wpedantic     " ## UseStrictISO_C         ##
C=$C"-Wall          " ## WarnAboutAnyWeirdCode  ##
C=$C"-Wextra        " ## "-Wall" WarningsExtra  ##
C=$C"-std=c99       " ## VersionOf_C_ToUse      ##
MY_COMMAND_STRING=$C  ############################

echo $MY_COMMAND_STRING
     $MY_COMMAND_STRING

C1=" gcc -o EXE.exe my_object_file.o "    
C2=" ./EXE.exe                       "    
C3=" rm my_object_file.o             "    
C4=" rm EXE.exe                      "  
$C1 && echo "OK:"$C1 || "FAIL:$C1"
$C2 && echo "OK:"$C2 || "FAIL:$C2"
$C3 && echo "OK:"$C3 || "FAIL:$C3"
$C4 && echo "OK:"$C4 || "FAIL:$C4"
##################################################
read -p "[END_OF_BUILD_SCRIPT:PressAnyKey]:"
##################################################
############################# SC[ hkmf-strict ] ##
##################################################

This is C99 code by the way. I try to write it avoiding any C99 specific features though.

Null values can be tricky to work with in JavaScript, but they are an important part of the language. In this article, we will discuss various ways you can check if there is a null value in an object or array in JavaScript.

The null values display that no object value is present. It is intentionally set to show that a variable has been declared but has not yet been given a value.

The primitive value is undefined, which is an unintended absence of any object value, which is comparable to null, that contrasts with the former. This is due to the fact that a declared variable that has not yet been given a value is undefined rather than null. There are many ways to check whether a value is null or not in JavaScript. Let’s discuss few ways one by one.

Using Object.keys()in JavaScript

The Object.keys() is a method in JavaScript that returns an array of the keys of an object. It takes one parameter, which is the object whose keys are to be returned. The order of the keys in the array is based on how they were added to the object; newer properties will appear after older ones. Object.keys can also be used for arrays, since arrays are objects as well and each element in an array has its own key (index).

Syntax

Following is the syntax for the Object.keys() method.

Object.keys(object)

Example

In the following example we are running the script using Object.keys.

<!DOCTYPE html>
<html>
<body>
   <script>
      var data = [{
         name: "AVATAR",
         Car: "AUDI",
         Bike: null,
         Location: null
      }, {
         name: "RAM",
         Car: "No",
         Bike: 'BULLET',
         Location: 'LA'
      }, ];
      data.forEach(function(v, i) {
         if (
            Object.keys(v).some(function(k) {
               return v[k] == null;
            })
         )
         document.write('Contains null value at: ', i + "<br>");
         else
         document.write(' data right', i);
      });
   </script>
</body>
</html>

When the script is executed, the event is triggered, allowing us to check the entire data set that was used in the script to determine whether the null present is present or not, and it will display null present in the first set of data and actual data in the second set of data right on the webpage based on our data.

Using JavaScript some()method

The some() method accepts a function as a parameter and tests, whether at least one element in the array passes the test implemented by the given function.

It returns true, when an element for which the provided function returns true; otherwise it returns false.

Syntax

Following is the syntax for some() method

array.some(function(value, index, arr), this)

Example

Considering the following example, where we are using the some() method to check whether null is present or not.

<!DOCTYPE html>
<html>
<body>
   <script>
      var arr = [
         { x : "1", y : "2", z : "3" },
         { x : "ram", y : "abc", z : "var" },
         { x : "abc", y : "def", z : null }
      ];
      function hasNull(element, index, array) {
         return element.x===null || element.y===null || element.z===null;
      }
      document.write( arr.some(hasNull) );
   </script>
</body>
</html>

On running the above script, the web-browser will display the value «true» on the webpage as the event gets triggered and checks whether the given array consists of null values or not, and it will display «true» as the condition was matched and the given array consists of null values.

Using JavaScript include() Method

The JavaScript include() method is used to load an external script or file into the current document. This method allows you to add scripts, libraries, and other files from outside of the existing HTML page. It can be used with both inline and external scripts. The include() method will execute the code in the specified file before continuing with the rest of your program.

Syntax

Following is the syntax for include()

string.includes(searchvalue, start)

Example

Let’s look into the following example where we are using the include() method

<!DOCTYPE html>
<html>
<body>
   <script>
      var nameArray = ["Jack", "rose", "Sam"];
      if (nameArray.includes(null) == true) {
         document.write("array contains null value");
      } else {
         document.write("array does not contains null value", "<br>");
      }
      var objectData = { name: null };
      if (Object.values(objectData).includes(null)) {
         document.write("object contains null value", "<br>");
      } else {
         document.write("object does not contains null value", "<br>");
      }
   </script>
</body>
</html>

When the script gets executed, the event gets triggered, which checks the data entered in the script to see whether, it contains null value or not and displays the value on the webpage. In the above case, it shows that the array does not contain null value and the object contains null value.

К примеру есть строчный массив String[] test;

if (test[] == null){
		Log.e("NULL - ", " ДА");
	} else {
		Log.e("NULL", "НЕТ");
	}

И оно выдаст что он не null, при этом если смотреть в debag то там All elements are null

Как собственно проверять массив на null ??

Как я понял можно проверить только по какому то индексу на null или же в цикле пройтись по всем индексам с проверкой на null, но есть ли более нормальный способ проверить массив на null без цикла и конкретного индекса ?

  1. Null Array in Java
  2. Array Contains Null Values
  3. Empty Array in Java
  4. Check Array Null Using Apache Commons Library in Java
  5. Check Array Null Using Java 8

Check Whether an Array Is Null/Empty in Java

This tutorial introduces how to check whether an array is null or empty in Java and also lists some example codes to understand the null checking process.

Null Array in Java

In Java, an array is an object that holds similar types of data. It can be null only if it is not instantiated or points to a null reference.

In this example, we have created two arrays. The array arr is declared but not instantiated. It does not hold any data and refers to a null reference (default value) assigned by the compiler. The array arr2 is declared and explicitly assigned to null to create a null array.

We can use this example to check whether the array is null or not.

public class SimpleTesting {

	String[] arr;
	String[] arr2 = null;
	
	public static void main(String[] args) {
		SimpleTesting obj = new SimpleTesting();
		if(obj.arr == null) {
			System.out.println("The array is null");
		}
		if(obj.arr2 == null) {
			System.out.println("The array2 is null");
		}
	}
}

Output:

The array is null
The array2 is null

Array Contains Null Values

This is the second scenario where an array contains null values. In that case, we can consider an array to be null.

Suppose, we have an array of string that can contain 5 elements. Since the array is not initialized then it holds null (default value) assigned by the compiler.

public class SimpleTesting {

	String[] arr = new String[5];

	public static void main(String[] args) {
		boolean containNull = true;
		SimpleTesting obj = new SimpleTesting();
		for(int i = 0; i<obj.arr.length; i++) {
			if(obj.arr[i] != null) {
				containNull = false;
				break;
			}
		}
		if(containNull) {
			System.out.println("Array is null");
		}
	}
}

Output:

Empty Array in Java

An array is empty only when it contains zero(0) elements and has zero length. We can test it by using the length property of the array object.

public class SimpleTesting {

	String[] arr = new String[0];

	public static void main(String[] args) {
		SimpleTesting obj = new SimpleTesting();
		if(obj.arr.length == 0) {
			System.out.println("The array is Empty");
		}
	}
}

Output:

Check Array Null Using Apache Commons Library in Java

If you are working with Apache then use ArrayUtils class to check whether an array is empty. The ArrayUtils class provides a method isEmpty() which returns a boolean value either true or false. For more info about apache library visit here.

import org.apache.commons.lang3.ArrayUtils;

public class SimpleTesting {

	String[] arr = new String[0];

	public static void main(String[] args) {
		SimpleTesting obj = new SimpleTesting();
		Boolean isEmpty = ArrayUtils.isEmpty(obj.arr);
		if(isEmpty) {
			System.out.println("Array is Empty");
		}
	}
}

Output:

Check Array Null Using Java 8

If you are working with Java 8 or higher version then you can use the stream() method of Arrays class to call the allMatch() method to check whether array contains null values or not.

This is the case when array contains null values.

import java.util.Arrays;
import java.util.Objects;

public class SimpleTesting {

	String[] arr = new String[10];

	public static void main(String[] args) {
		SimpleTesting obj = new SimpleTesting();
		Boolean containNull = Arrays.stream(obj.arr).allMatch(Objects::nonNull);
		if(!containNull) {
			System.out.println("Array is null");
		}
	}
}

Output:

Понравилась статья? Поделить с друзьями:
  • Как найти пароли от своих аккаунтов
  • Как составить письменно характеристику с работы
  • Демон тулс доступ запрещен как исправить
  • Как найти инн по паспорту украина
  • Как найти нору сурка