Abnormal ArrayList NullPointerException
in
Programming Questions
•
3 years ago
Here is the code:
(the code is far incomplete, but it is not the matter)
- final int ACT_ADD = 1;
- final int ACT_SUB = 2;
- final int ACT_MUL = 3;
- final int ACT_DIV = 4;
- final int ACT_NON = 5; //in case if an element is not an operation but a simple number
- //...
- //and so on if needed
- final int VARTYPE_INT = 1;
- final int VARTYPE_FLOAT = 2;
- final int STRUC_ELEMENT_A = 0;
- final int STRUC_ELEMENT_B = 1;
- final int STRUC_VARTYPE = 2;
- final int STRUC_VALUE = 3;
- final int STRUC_ACTION = 4;
- class IntVal
- {
- int value;
- IntVal(int val)
- {
- value = val;
- }
- }
- class Element
- {
- ArrayList structure;
- // [Element a][Element b][this.Element VARTYPE][this.Element value][Action]
- Element(Element a, Element b, int vartype, int value, int action)
- {
- ArrayList structure = new ArrayList();
- structure.add(a);
- structure.add(b);
- structure.add(new IntVal(vartype));
- structure.add(new IntVal(value));
- structure.add(new IntVal(action));
- println( ((IntVal)structure.get(STRUC_ACTION)).value);
- println("Evaluating: " + (Element)structure.get(1));
- }
- void Evaluate()
- {
- // println("Evaluating: " + (Element)structure.get(1));
- int evalA = 0;
- int evalB = 0;
- IntVal actObj;
- int act = 0;
- actObj = (IntVal)this.structure.get(STRUC_ACTION);
- act = actObj.value;
- if(act != ACT_NON)
- {
- a = (Element) structure.get(STRUC_ELEMENT_A);
- b = (Element) structure.get(STRUC_ELEMENT_B);
- a.Evaluate();
- b.Evaluate();
- evalA = ( (IntVal)a.structure.get(STRUC_ELEMENT_A) ).value;
- evalB = ( (IntVal)b.structure.get(STRUC_ELEMENT_B) ).value;
- }
- switch( ((IntVal)structure.get(STRUC_ACTION)).value)
- {
- case ACT_ADD:
- this.structure.set( STRUC_VALUE, (int) (evalA + evalB) );
- break;
- case ACT_SUB:
- this.structure.set( STRUC_VALUE, (int) (evalA - evalB) );
- break;
- case ACT_MUL:
- this.structure.set( STRUC_VALUE, (int) (evalA * evalB) );
- break;
- case ACT_DIV:
- this.structure.set( STRUC_VALUE, (int) (evalA / evalB) );
- break;
- case ACT_NON:
- break;
- }
- }
- }
- Element five = new Element(null,null,VARTYPE_INT,5, ACT_NON);
- Element six = new Element(null,null,VARTYPE_INT,6, ACT_NON);
- Element addition = new Element(five,six,VARTYPE_INT,0, ACT_ADD);
- void draw()
- {
- addition.Evaluate();
- println( ((IntVal)addition.structure.get(STRUC_VALUE)).value);
- }
If I compile it in this form, I get NPE on line 53 and on line 47(if uncommented). However, if i take away the ArrayList word marked red, the NPE only comes up on line 63. My question is: why am I getting this NPE? And most important is the question what don't I understand about ArrayList that makes it behave so strange to me?
1