相关文章推荐
纯真的显示器  ·  ResourceHandlerRegistr ...·  8 月前    · 
安静的弓箭  ·  关于 MyBatis-Plus ...·  10 月前    · 
爱搭讪的猴子  ·  Spring ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

return 1 or 0?

If I can add null values to an ArrayList , can I loop through only the indexes that contain items like this?

for(Item i : itemList) {
   //code here

Or would the for each loop also loop through the null values in the list?

Note that IntelliJ hides those nulls, which can be disabled - stackoverflow.com/questions/44430633/… – Dror Fichman May 4, 2022 at 11:04

Yes, you can always use null instead of an object. Just be careful because some methods might throw error.

It would be 1.

Also nulls would be factored in in the for loop, but you could use

for (Item i : itemList) {
    if (i != null) {
       //code here
                For example, List.of(...) will throw if the supplied value is null. This is dumb -- just putting it out there. It's perfectly legit to have a null value in a list!
– Josh M.
                Jan 27, 2022 at 14:03
                List.of(...) will throw exception however Stream.of(null, "a").toList() works perfectly fine.
– thoredge
                Nov 8, 2022 at 9:04
                @JoshM. Weirdly enough, Collections.singletonList() does allow null, which means that the of method is even more "off". Anyway, if you need to create a list of one element that may be null then singletonList may help.
– Maarten Bodewes
                Dec 13, 2022 at 11:22

You can add nulls to the ArrayList, and you will have to check for nulls in the loop:

for(Item i : itemList) {
   if (i != null) {

itemsList.size(); would take the null into account.

 List<Integer> list = new ArrayList<Integer>();
 list.add(null);
 list.add (5);
 System.out.println (list.size());
 for (Integer value : list) {
   if (value == null)
       System.out.println ("null value");
       System.out.println (value);

Output :

null value

You could create Util class:

public final class CollectionHelpers {
    public static <T> boolean addNullSafe(List<T> list, T element) {
        if (list == null || element == null) {
            return false;
        return list.add(element);

And then use it:

Element element = getElementFromSomeWhere(someParameter);
List<Element> arrayList = new ArrayList<>();
CollectionHelpers.addNullSafe(list, element);
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.