Java object array, java Array
The java object array is a little different from the ordinary array. In fact, the underlying principle is the same. We must remember to create an object using the object array. Otherwise, a null pointer exception will be reported,
I have already met it twice, and every time it has been a waste of a long time. Now I am posting an initialization process. You can check it out. Please remember that the new object should not be in the new array only.
public class Student
{
private String username;
private int num;
public Student(String username, int num)
{
this.username = username;
this.num = num;
}
public static void main(String[] args)
{
Student s[] = new Student[10];
for (int i = 0; i < s.length; i++)
{
s[i] = new Student(i + "", i);
System.out.println(s[i]);
}
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public int getNum()
{
return num;
}
public void setNum(int num)
{
this.num = num;
}
@Override
public String toString()
{
return this.num + " " + this.username;
}
}
For an array of objects in Java
First: Data [] d = new Data [3]; create an object array. Three Data objects in the array have been initialized to null but are not instantiated.
D [I] = new Data (); is used for instantiation.
The reason for java. lang. NullPointerException is that the getData () method is called without instantiation.
Java object array Definition
Public class Student
{
Private String username;
Private int num;
Public Student (String username, int num)
{
This. username = username;
This. num = num;
}
Public static void main (String [] args)
{
Student s [] = new Student [10];
For (int I = 0; I <s. length; I ++)
{
S [I] = new Student (I + "", I );
System. out. println (s [I]);
}
}
Public String getUsername ()
{
Return username;
}
Public void setUsername (String username)
{
This. username = username;
}
Public int getNum ()
{
Return num;
}
Public void setNum (int num)
{
This. num = num;
}
@ Override
Public String toString ()
{
Return this. num + "" + this. username;
}
}