简体   繁体   中英

Returning the number of items in a list

I have a method called public int getSize() and it is suppose to return the number of items in the list. the instance variable is private Listable[] items; I thought it would just 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 nullpointerexception on the for (int i = 0; i < items.length; i++){ line

I don't think it likes items.length for some reason. I'm not getting any errors in Java. How should I do this?

i already tried return items.length;

that didnt work either.

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

I saw this article when I was browsing the web it contains the 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);

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

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

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

items = new Listable[10];

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM