Return the number of items in a list

I have a method called public int getSize() , and it should return the number of elements in the list. private Listable[] items; variable variable private Listable[] items; I thought it would be something like this:

 int size = 0; for (int i = 0; i < items.length; i++){ size++; } return size; 

But when I run it through these tests, I get this nullpointer exception in the for (int i = 0; i < items.length; i++){ line for (int i = 0; i < items.length; i++){

I do not think that he somehow likes items.length . I am not getting any errors in Java. How can I do it?

I already tried returning items.length;

which didn't work either.

+6
source share
3 answers

I believe that you forgot to initialize the variable. Try something like:

 items = new Listable[10]; 

For your getSize () method, you just need to return items.length

+2
source

http://www.easywayserver.com/blog/java-how-to-get-size-of-list/

I saw this article when I was browsing a website, it contains code that implements the list.size () method.

 List<String> ls=new ArrayList<String>(); ls.add("one"); ls.add("Three"); ls.add("two"); ls.add("four"); int sizeOfList=ls.size(); System.out.println("Size of List :"+sizeOfList); 
+3
source

Since MeBigFatGuy commented (+1), your items variable is null. In fact, his comment completely answers your question ... Here is an implementation that should do what you want:

 public int getSize() { return items == null ? 0 : items.length; } 
+2
source

Source: https://habr.com/ru/post/886591/


All Articles