Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: ListA.addAll(ListB) fires NullPointerException?

The err part is Capitalized in the code, it also comes in foreaching. Because of the abstract list, it cannot be initialized, declaration is in a static field. The lists have the same type.

import java.util.*;

public class Test
{

        public static final List<String> highPrio = Arrays.asList("*","/");
        public static List<String> ops;

        public static void main(String[] args)
        {
                //ERROR HERE, why do it throw nullPointer?
                ops.addAll(highPrio);

                for(String s : ops)
                {
                        System.out.println(s);
                }
        }
}

Why not new List() in the initialization?

The reason for not initialization was the inability to use = new List<String>(). I cannot see a logic not allowing it. It must have something to do with intrinsic factors such as data strucs or something else.

Test.java:7: java.util.List is abstract; cannot be instantiated public static List<String> ops = new List<String>();

Why list is an interface?

I know that many data strucs such as stack implements list. But I cannot understand why List is an interface and why not Table for example. I see list as a primitive structure with which you can implement other structures. Interface is a thing where you can specify requirements for a structure. Is the primitivenness or extensivenss reason for being an interface?

like image 262
hhh Avatar asked Dec 02 '22 05:12

hhh


2 Answers

Because ops is null. The fact that List is an interface does not mean you can't initialize the field:

public static List<String> ops = new ArrayList<String>();

List is an interface because there are multiple ways of implementing it while providing the same contract (though different performance characteristics). For instance, ArrayList is array-backed, while LinkedList is a linked list.

like image 72
Matthew Flaschen Avatar answered Dec 04 '22 09:12

Matthew Flaschen


You need to instantiate the ops list.

public static List<String> ops = new ArrayList<String>();

or another list type of your choosing.

like image 30
Rob Goodwin Avatar answered Dec 04 '22 07:12

Rob Goodwin