I want to make an array of size 150 of the class Info
public class Info {
int Group;
String Name;
}
But I have the exception occur after
public class Mover {
static Info[] info=new Info[150];
public static void main(String[] args) {
info[0].Group=2;//I get error here
}
}
I'm not sure if there is a better way to do what a want to do, but I don't want to use a multidimensional array. I'm simply trying to add information to the group, so I'm confused.
doing new Info[150] simply instantiates an array of size 150. All elements within the array have not been instantiated and are therefore null.
So when you do info[0] it returns null and you're accessing null.Group.
You have to do info[0] = new Info() first.
This static Info[] info=new Info[150]; is creating an array of 150 objects of type info pointing to NULL.
You have to do this to get this working
for(int i = 0; i< 150; i++)
info[i] = new Info();
Then you can use these objects
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have been trying to create an array of a class containing two values, but when I try to apply a value to the array I get a NullPointerException.
public class ResultList {
public String name;
public Object value;
}
public class Test {
public static void main(String[] args){
ResultList[] boll = new ResultList[5];
boll[0].name = "iiii";
}
}
Why am I getting this exception and how can I fix it?
You created the array but didn't put anything in it, so you have an array that contains 5 elements, all of which are null. You could add
boll[0] = new ResultList();
before the line where you set boll[0].name.
ResultList[] boll = new ResultList[5];
creates an array of size=5, but does not create the array elements.
You have to instantiate each element.
for(int i=0; i< boll.length;i++)
boll[i] = new ResultList();
As many have said in the previous answers, ResultList[] boll = new ResultList[5]; simply creates an array of ResultList having size 5 where all elements are null. When you are using boll[0].name, you are trying to do something like null.name and that is the cause of the NullPointerException. Use the following code:
public class Test {
public static void main(String[] args){
ResultList[] boll = new ResultList[5];
for (int i = 0; i < boll.length; i++) {
boll[i] = new ResultList();
}
boll[0].name = "iiii";
}
}
Here the for loop basically initializes every element in the array with a ResultList object, and once the for loop is complete, you can use
boll[0].name = "iiii";
I think by calling
ResultList[] boll = new ResultList[5];
you created an array which can hold 5 ResultList, but you have to initialize boll[0] before you can set a value.
boll[0] = new ResultList();
ResultList p[] = new ResultList[2];
By writing this you just allocate space for a array of 2 elements.
You should initialize the reference variable by doing this:
for(int i = 0; i < 2; i++){
p[i] = new ResultList();
}
Furthermore, you can prove this to yourself by adding a debug line to your class, such as:
public class ResultList {
public String name;
public Object value;
public ResultList() {
System.out.println("Creating Class ResultList");
}
}
Whenever an object is created, one of its constructors must be called (if there is no constructor, a default one is created automatically, similar to the one you already have in your class). If you only have one constructor, then the only way to create an object is to call that constructor. If the line
ResultList[] boll = new ResultList[5];
really created 5 new objects, you would see your debug line appear on the console 5 times. If it does not, you know the constructor is not being called. Notice also that the above line does not have a parameter list with open and close parentheses "()" so it is not a function call - or constructor call. Instead, we are only referring to the type. We are saying: "I need space for an array of ResultList objects, up to 5 total." After this line, all you have is empty space, not objects.
As you try out various fixes, the debug line will help confirm you are getting what you want.
class ResultList {
public String name;
public Object value;
public ResultList() {}
}
public class Test {
public static void main(String[] args){
ResultList[] boll = new ResultList[5];
boll[0] = new ResultList(); //assign the ResultList objet to that index
boll[0].name = "iiii";
System.out.println(boll[0].name);
}
}
Till you have created the ResultSet Object but every index is empty that is pointing to null reference that is the reason you are getting null.
So just assign the Object on that index and then set the value.
first of all you have created 5 element of ResultList type, but when inserting value you are inserting name and value wrong. you could use constructor to create and insert values to the array elements.
class ResultList {
public String name;
public Object value;
public ResultList(String name,Object value){
this.name = name;
this.value = value;
System.out.println(name+" --- "+value);
}
}
public static void main(String[] args) {
ResultList[] boll = new ResultList[5];
boll[0] = new ResultList("myName","myValue");
}
Either you can try this scenario or you can the make the variable "name" static in ResultList Class. So when the ResultList[] boll = new ResultList[5]; gets executed at that time all the variable from that class will gets assign
public static void main(String[] args){
ResultList[] boll = new ResultList[5];
boll[0] = new ResultList();
boll[0].name = "iiii";
System.out.println(boll[0].name);
}
public class ResultList {
public static String name;
public Object value;
public ResultList() {}
}
I want to know how do you access an attribute in a class inside an array like an example below:
import java.util.*;
public class DogTest{
public class Dog {
int Quantity;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Dog dogs[] = new Dog[15];
for ( int i = 1; i <=15; i++){
System.out.println("Enter number of Dogs ");
dogs[i].Quantity = scan.nextInt();
}
}
}
The code above does not seem to work. dogs[i].Quantity is derived from my C++ knowledge by the way.
Error msg:
Exception in thread "main" java.lang.NullPointerException
Is my structure wrong? Or there is another way to do it?
Arrays start at position 0. So at end of your loop you try to access dogs[15] which does not exist. Essentially an array of size 15 is accessed by numbers 0-14. This may be the problem.
Try starting loop like this
for(int i=0;i<15;i++)
{
}
First of all declare a class for itself, not as an inner class like you did.Never give fields first uppercase letter, that is naming convention.
public class Dog{
int quantity;
}
And, your actual problem is that when you declare an array of dogs, you declared an array of size, in your case, 15 but it doesn't contain any objects. You just initialised and array which holds 15 nulls and can be filled with Dog objects. And because that you get a null pointer exception.So, first you should fill your array with the dog objects, something like this:
for (int i = 0; i < dogs.length; i++){
dogs[i] = new Dog(); // calls a constructor for Dog object
}
And, after that, you can access your objects trough for loop to change a field quantity
for(int i = 0; i < dogs.length; i++){
dogs[i].quantity = i;
}
Also, I would recommend to make your fields private and make getter and setter methods for accessing and changing their value.
Edit: And yes, mikekane was right about the array size, you would get an ArrayIndexOutOfBoundsException just after you fix this problem with the code you've tried to solve it...
How can I use an array within a method that was called in as a parameter for a different constructor initializer in the same class?
For example:
private static Initialize(int[] array)
private static void Display()
I want to take the array called in above in the Initialize method and use it in the Display method. I kept getting null reference pointer errors when I first tried it. Thank you for any help in advance!!
You can declare your array outside the method Initialize to have access in your class body.
For example:
private static int[] array;
private static Initialize() {
array = new int[] { 1, 2, 3 };
}
private static void Display() {
for (int i : array) {
System.out.println(i);
}
}
Assign the array to a class variable when Initialize() is called.
private static int[] array;
private static Initialize(int[] array) {
this.array=array;
}
The array can then be referenced as array as long as Initialize has already been called.
You probably mean how you can transfer one instance of array between classes.
Simplest way is using simple composition(in this case for one Array, but you can use it on n number of object):
First you need to define new class, which constructor takes in the array data as parameter and define the uninitialized array(which serves as a bridge between classes and also a container for the instantiated data).
public class TransferArray {
private String[] transferredArray;
public TransferArray(String[] originalArray){
transferredArray = originalArray;
}
String[] getArray() {
return transferredArray;
}
}
now to test this work, use this in the main class(both arrays now printing Hello)
String[] originalArray = {"Hello"};
TransferArray transfer = new TransferArray(originalArray);
String[] newArray = transfer.getArray();
System.out.println(originalArray[0]);
System.out.println(newArray[0]);
I would like to have a static array in a Java class with an undetermined size initially. The intent is to use the array to store values calculated in a method in one class and used in another.
E.g. the 'TwoDX(Y)Pos[] arrays defined here:
public class DisplayObject {
// Each object is defined by a color, number of vertices, and dim (2,3,4) coordinate vertex locations
// Use dim to verify that the right number of vertices were sent
public static int Dim=3;
public static int RefDist=100;
public static int TwoDXpos[];
public static int TwoDYpos[];
}
And used here:
public void render2D(){
for (int cnt=0; cnt<this.NoOfVerts; cnt++){
if (this.coords[cnt*Dim+2] < RefDist) {break;}
TwoDXpos[cnt]=this.coords[cnt*Dim]/(this.coords[cnt*Dim+2]/RefDist);
TwoDYpos[cnt]=this.coords[cnt*Dim+1]/(this.coords[cnt*Dim+2]/RefDist);
}
}
But, since the original static references have no defined size, they reference Null pointers at execution.
How would you create such arrays?
I would like to have a static array in a java class with an initially undetermined size.
Sorry.
That isn't possible in Java. JLS-10.3. Array Creation says (in part)
The array's length is available as a final instance variable length.
Alternative
However, you could have a List of Foo(s) like
List<Foo> al = new ArrayList<>();
Use ArrayList instead of arrays.
Your code should look like this:
public class DisplayObject {
// Each object is defined by a color, number of vertices, and dim (2,3,4) coordinate vertex locations
// Use dim to verify that the right number of vertices were sent
public static int Dim=3;
public static int RefDist=100;
public static ArrayList<Integer> TwoDXPos;
public static ArrayList<Integer> TwoDYPos;
}
and the render 2d method:
public void render2D(){
for (int cnt=0; cnt<this.NoOfVerts; cnt++){
if (this.coords[cnt*Dim+2] < RefDist) {break;}
TwoDXpos.get(cnt)=this.coords[cnt*Dim]/(this.coords[cnt*Dim+2]/RefDist);
TwoDYpos.get(cnt)=this.coords[cnt*Dim+1]/(this.coords[cnt*Dim+2]/RefDist);
}
}
The advantage of using ArrayList is that you can use its add(item) method to change its size dynamically.
Hope it helps!
public void render2D() {
TwoDXpos = new int[this.NoOfVerts];
TwoDYpos = new int[this.NoOfVerts];
for (int cnt = 0; cnt < this.NoOfVerts; cnt++) {
if (this.coords[cnt * Dim + 2] < RefDist) {
break;
}
TwoDXpos[cnt] = this.coords[cnt * Dim] / (this.coords[cnt * Dim + 2] / RefDist);
TwoDYpos[cnt] = this.coords[cnt * Dim + 1] / (this.coords[cnt * Dim + 2] / RefDist);
}
}
and pls following Java naming rules to name your variable: http://www.iwombat.com/standards/JavaStyleGuide.html#Attribute%20and%20Local%20Variable%20Names
Short answer is you need to initialize the array before using them.
To avoid memory leakage, you should set its size at initialization. e.g.10.
public static int TwoDXpos[] = new int[10];
public static int TwoDYpos[] = new int[10];
If the array size changes, you should use ArrayList because its size is automatically managed by JVM
You can't use an array whose size is not determined. You should initialize the array size before method render2D() called. May be you could use this.NoOfVerts as the array size.
If you are going to use an array, you should initialize it by mentioning the size of the array in order to allocate memory before using it.
public static int TwoDXpos[];
public static int TwoDYpos[];
Any access on this would throw NullPointerException because the memory for this not allocated and object defintion has not happened at all.
You ought to remember this on array (or any objects for that sake) "Initialize before you access/use them"
If you worry is about that you are not sure about the number of elements upfront, you should use utilities like ArrayList which is provided in Java Collection Framework. This would take care dynamically adjusting the size as the number of elements increases.
Alternative Approach
private static List<Integer> twoDXPos = new ArrayList<Integer>();
private static List<Integer> twoDYPos = new ArrayList<Integer>();
and then itemes can be added using add method in java.util.Collection class. (Refer the link I gave above)
twoDXPos.add(1) //1 is an example integer here to illustrate
twoDYPos.add(1) //1 is an example integer here to illustrate
I'm getting a null pointer exception on the following code (part of a larger program - the exception is thrown on the line where "add" is called).
public class A
{
static ArrayList<Integer> sets[];
public static void main(String[] args)
{
sets = new ArrayList[5];
sets[0].add(1);
}
}
I also do not understand why the compiler is requiring me to make any class level variables static (e.g. the ArrayList). As far as I can tell, these things shouldn't be in a static context (in terms of coding practice, not compiler problems) and yet the compiler is requiring it.
Thanks in advance.
sets = new ArrayList[5];
Just fills 5 spots with null
You need to explicitly set ArrayList() for each position before doing add() call.
Example:
sets[0] = new ArrayList<Integer>();
sets[0].add(5);
The line
sets = new ArrayList[5];
allocates the array, but does not place an ArrayList in any element of the array.
You would need
sets[0] = new ArrayList<Integer>();
sets[0].add(1);
It's because your array is initialized with null values.
//it will initialize sets variable
sets = new ArrayList[5];
//but set[0], set[1]... and on are null
You should initialize the array items as well before using them
sets[0] = new ArrayList<Integer>();
sets[0].add(1);
Also, for a better design, you should program oriented to interfaces instead of the class. See What does it mean to "program to an interface"? for more info.
In short, your code should look like
public class A {
static List<Integer> sets[];
public static void main(String[] args) {
sets = new List[5];
sets[0] = new ArrayList<Integer>();
sets[0].add(1);
//extending your code in order to use more than one value of the List array
sets[1] = new ArrayList<Integer>();
sets[1].add(20);
for(List<Integer> list : sets) {
if (list != null) {
System.out.println(list.get(0));
}
}
}
}