Checking size of stack (ArrayList) in Java? -


i'm trying implement stack array list. bluej tells me "size" has private access in java.util.arraylist though array list public, when i'm compiling.

int stacklength = stackstorage.size; system.out.println(+stacklength); 

and if change line to..

int stacklength = stackstorage.size(); 

the program compiles , nullpointerexcetion when run function.

i don't understand why happening because value cannot manually assigned because value needs come stack size.

any appreciated, cheers.

you can't directly call variable (because it's private field). should use stackstorage.size() instead. make sure stackstorage instantiated.


you have:

arraylist<object> stackstorage; 

however must instantiate somewhere so:

stackstorage = new arraylist<object>(); 

this may done on same line:

arraylist<object> stackstorage = new arraylist<object>(); 

once have created arraylist note still doesn't have elements in it. in order add integer array do:

stackstorage.add(number); 

and after that, if call stackstorage.size() should return 1, meaning there's 1 element in arraylist. if wish add more, use add() method. make sure add same object instantiated with. can't store string in arraylist<integer> example.

full-code example:

arraylist<integer> stackstorage = new arraylist<integer>(); stackstorage.add(10); //now has value `10` in `index[0]` system.out.println("index[0]: " + stackstorage.get(0)); //prints 10 system.out.println("stackstorage.size() = " + stackstorage.size()) //prints 1 

in case replace object integer if wish store integers. nullpointerexception means object still null when tried call size(). should solve issue. if you're not sure null or don't quite understand npe(nullpointexception) suggest reading , if have further difficulties, posting here.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -