Why does Java never reach the end of this if/else?

82 Views Asked by At

I've been scratching my head at this for hours now, but I can't seem to figure this one out. I'm writing a program that has a constant loop going in a Thread, which occasionally sends back data to another part of the program using an Arraylist.

I only want to send this data back after I have gathered 11 items in my arraylist. So I used this code:

//The rest of the loop in which i gather the values for key and velocity.

    notenbuffer.add(new Noot(key,velocity));
    if (notenbuffer.size() > 10){
    System.out.println("Notenbuffer > 10, verstuur data");
        
    if (notenbuffer.isEmpty()){
          System.out.println("buffer is empty!");

    }
    else {
          usbRead.writeNotes(notenbuffer);
          System.out.println("emptied the buffer!");
          notenbuffer.clear();
    }
        
    }

Now for some weird reason the program never empties the Arraylist, and just keeps on adding items to it. I've checked and it does in fact reach the usbRead.writeNotes(notenbuffer) part because this function gets called correctly. When I use the debugger it simply skips to the beginning of the loop after this function was called.

Is there a way in which I can empty an Arraylist once it reaches a certain size?

Edit: I made a logic error by writing if (notenbuffer.isEmpty()) this will always be false because I am already in an if statement which requires this to be false.

1

There are 1 best solutions below

0
On

Did you put your second if inside your first by accident? (The missing indentation seems to suggest so). Having if (notenbuffer.isEmpty()) inside the if (notenbuffer.size() > 10) block makes no sense at all logically. After all if your List size is > 10 then the list is obviously not empty. So if (notenbuffer.isEmpty()) can never be true at all. – OH GOD SPIDERS 15 mins ago

This was indeed the problem. Removing this exposed an NoClassDefFoundError that needed resolving.