Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java NullPointerException when adding to ArrayList?

Tags:

My code is throwing a NullPointerException, even though the object seems to properly exist.

public class IrregularPolygon {      private ArrayList<Point2D.Double> myPolygon;      public void add(Point2D.Double aPoint) {         System.out.println(aPoint); // Outputs Point2D.Double[20.0, 10.0]         myPolygon.add(aPoint); // NullPointerException gets thrown here     } }  // Everything below this line is called by main()      IrregularPolygon poly = new IrregularPolygon();     Point2D.Double a = new Point2D.Double(20,10);     poly.add(a); 

Why is this happening?

like image 647
waiwai933 Avatar asked Oct 16 '10 17:10

waiwai933


People also ask

How do I fix Java Lang NullPointerException in Java?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

What is the most likely cause of NullPointerException?

What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.

Do Arraylists use pointers?

The Java collection classes, including ArrayList, have one major constraint: they can only store pointers to objects, not primitives. So an ArrayList can store pointers to String objects or Color objects, but an ArrayList cannot store a collection of primitives like int or double.

How do I ignore Java Lang NullPointerException?

Answer: Some of the best practices to avoid NullPointerException are: Use equals() and equalsIgnoreCase() method with String literal instead of using it on the unknown object that can be null. Use valueOf() instead of toString() ; and both return the same result. Use Java annotation @NotNull and @Nullable.


2 Answers

based on the parts of the code you provided, it looks like you haven't initialized myPolygon

like image 157
Brad Mace Avatar answered Oct 19 '22 13:10

Brad Mace


private ArrayList<Point2D.Double> myPolygon = new ArrayList<Point2D.Double>(); 
like image 20
Cristian Avatar answered Oct 19 '22 13:10

Cristian