简体   繁体   中英

trying to find total filled elements in array but i dont know how to output the correct amount, should be zero

in title im trying to find how many String elements are in the array im using, i have the size set to a explicit length variable that i can set to whatever i want, but im trying to write a function that returns the actual total filled element in that array

   public int size(){             
       while (this.count < bag.length) { 
           count++;   
       }
       return count;
   }

my attempt so far, which doesn't work because here we are assuming that my array is set to size 10, all I get in the test cases in 10 for the count which isn't correct because i haven't actually added any strings to it yet, and that is to be done in a different method how can I write this to return the actually filled slots which should be zero as of now

Do it as follows:

public int size() {
    int count=0;
    for(String s:bag) {
        if (s!=null) {
            count++;
        }
    }
    return count;
}

You have to check, whether or not each element within that array is not null and then count those:

public int size() {
  return Arrays.stream(bag).filter(Objects::nonNull).count();
}

Edit: Added the suggestion of @Arvind Kumar Avinash. Thank you

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