how to add elements to an Arraylist of an object in Java?
So, I have a class with some vectors and I’m trying to add elements to those vectors. But, when I try to push elements with add method, it throws NullPointerException. I’m using eclipse as editor.
package com.vogella.eclipse.ide.first; import java.util.Vector; public class Qr { // The class int x,y; Vector<String> at = new Vector<String>(); } public class cls { public static void main(String[] args) { Qr[] var = new Qr[5]; String q = new String("ggg"); var[1].at.add(q); System.out.print("gg"); } }
It throws an error
Exception in thread "main" java.lang.NullPointerException at sf.eclipse.ide.first.nfd.main(nfd.java:89)
Is this correct or am I doing something wrong?
You need to make following changes to your code to make it work :
-
Create a constructor to initialize the variable of the class Qr.
-
Once you have created the Qr array, you need to initialize , individual element of the Qr array.
class Qr { // The class int x,y; Vector<String> at; Qr(){ //Step1 this.x=0; this.y=0; this.at = new Vector<String>(); } }
Main method:
public static void main(String[] args) { Qr[] var = new Qr[5]; var[1] = new Qr(); // Step 2 String q = new String("ggg"); var[1].at.add(q); System.out.print("gg"); }