Como verificar se o elemento da matriz é nulo para evitar NullPointerException em Java
-
06-07-2019 - |
Pergunta
Eu tenho uma matriz parcialmente nfilled de objetos, e quando eu iterate através deles eu tentei verificar se o objeto selecionado é null
antes de eu fazer outras coisas com ele. No entanto, mesmo o ato de verificar se é null
parece através de um NullPointerException
. array.length
irá incluir todos os elementos null
também. Como você ir sobre a verificação de elementos null
em uma matriz? Por exemplo, no código a seguir irá lançar uma NPE para mim.
Object[][] someArray = new Object[5][];
for (int i=0; i<=someArray.length-1; i++) {
if (someArray[i]!=null) { //do something
}
}
Solução
Você tem mais acontecendo do que você disse. Eu corri o seguinte teste expandido do seu exemplo:
public class test {
public static void main(String[] args) {
Object[][] someArray = new Object[5][];
someArray[0] = new Object[10];
someArray[1] = null;
someArray[2] = new Object[1];
someArray[3] = null;
someArray[4] = new Object[5];
for (int i=0; i<=someArray.length-1; i++) {
if (someArray[i] != null) {
System.out.println("not null");
} else {
System.out.println("null");
}
}
}
}
e obteve o resultado esperado:
$ /cygdrive/c/Program\ Files/Java/jdk1.6.0_03/bin/java -cp . test
not null
null
not null
null
not null
Você possivelmente tentando verificar os comprimentos de someArray [índice]?
Outras dicas
Ela não tem.
Veja abaixo. O programa que você postou é executado como deveria.
C:\oreyes\samples\java\arrays>type ArrayNullTest.java
public class ArrayNullTest {
public static void main( String [] args ) {
Object[][] someArray = new Object[5][];
for (int i=0; i<=someArray.length-1; i++) {
if (someArray[i]!=null ) {
System.out.println("It wasn't null");
} else {
System.out.printf("Element at %d was null \n", i );
}
}
}
}
C:\oreyes\samples\java\arrays>javac ArrayNullTest.java
C:\oreyes\samples\java\arrays>java ArrayNullTest
Element at 0 was null
Element at 1 was null
Element at 2 was null
Element at 3 was null
Element at 4 was null
C:\oreyes\samples\java\arrays>
String labels[] = { "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" };
if(Arrays.toString(labels).indexOf("null") > -1) {
System.out.println("Array Element Must not be null");
(or)
throw new Exception("Array Element Must not be null");
}
------------------------------------------------------------------------------------------
For two Dimensional array
String labels2[][] = {{ "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" },{ "MH", "FG", "AP", "KL", "CH", "MP", "GJ", "OR" };
if(Arrays.deepToString(labels2).indexOf("null") > -1) {
System.out.println("Array Element Must not be null");
(or)
throw new Exception("Array Element Must not be null");
}
------------------------------------------------------------------------------------------
same for Object Array
String ObjectArray[][] = {{ "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" },{ "MH", "FG", "AP", "KL", "CH", "MP", "GJ", "OR" };
if(Arrays.deepToString(ObjectArray).indexOf("null") > -1) {
System.out.println("Array Element Must not be null");
(or)
throw new Exception("Array Element Must not be null");
}
Se você quiser encontrar um elemento nulo particular, você deve usar loop for como acima disse.
O código dado funciona para mim. Observe que someArray [i] é sempre nulo desde que você não inicializou a segunda dimensão da matriz.
Bem, em primeiro lugar que o código não compila.
Depois de retirar o ponto e vírgula extra após i ++, ele compila e funciona muito bem para mim.
O código de exemplo não lançar uma NPE. (Há também não deve ser um ';' atrás do i ++)
Combate se o código está compilando ou não, eu diria que criar uma matriz de 2 valores sixe 5 add e imprimi-los, você vai obter os dois valores e outros são nulos. A questão é que, embora o tamanho é 5, mas existem 2 objetos na matriz. Como encontrar quantos objetos estão presentes no array
public static void main(String s[])
{
int firstArray[] = {2, 14, 6, 82, 22};
int secondArray[] = {3, 16, 12, 14, 48, 96};
int number = getCommonMinimumNumber(firstArray, secondArray);
System.out.println("The number is " + number);
}
public static int getCommonMinimumNumber(int firstSeries[], int secondSeries[])
{
Integer result =0;
if ( firstSeries.length !=0 && secondSeries.length !=0 )
{
series(firstSeries);
series(secondSeries);
one : for (int i = 0 ; i < firstSeries.length; i++)
{
for (int j = 0; j < secondSeries.length; j++)
if ( firstSeries[i] ==secondSeries[j])
{
result =firstSeries[i];
break one;
}
else
result = -999;
}
}
else if ( firstSeries == Null || secondSeries == null)
result =-999;
else
result = -999;
return result;
}
public static int[] series(int number[])
{
int temp;
boolean fixed = false;
while(fixed == false)
{
fixed = true;
for ( int i =0 ; i < number.length-1; i++)
{
if ( number[i] > number[i+1])
{
temp = number[i+1];
number[i+1] = number[i];
number[i] = temp;
fixed = false;
}
}
}
/*for ( int i =0 ;i< number.length;i++)
System.out.print(number[i]+",");*/
return number;
}
Você pode fazê-lo em uma linha de código (sem declaração de matriz):
object[] someArray = new object[]
{
"aaaa",
3,
null
};
bool containsSomeNull = someArray.Any(x => x == null);