The_Lost_Avatar
The_Lost_Avatar

Reputation: 988

Remove from ArrayList not working

for(JCheckBox currentCheckBox : imagesToBeImportedCheckBox){ 
    if(currentCheckBox.isSelected()){
                    System.out.println("The text Box selected for removing are"+currentCheckBox.getText());
                }

             }
            for(JCheckBox currentCheckBox : imagesToBeImportedCheckBox){

                if(currentCheckBox.isSelected()){
                    System.out.println("I am entering in the loop where this image has to be removed "+currentCheckBox.getText());
                    imagesToBeImported.remove(currentCheckBox.getText());

                }

             }
            for(ResourceListObject currentImage : imagesToBeImported){

                System.out.println("After removing the images left are "+currentImage.getName());

             }

and here's the output

The text Box selected for removing are aix71b

The text Box selected for removing are Migration-image

I am entering in the loop where this image has to be removed aix71b

I am entering in the loop where this image has to be removed Migration-image

After removing the images left are aix71b

After removing the images left are Migration-image

Upvotes: 0

Views: 128

Answers (2)

Rahul
Rahul

Reputation: 45090

Looking at your code, most likely, this is the problem.

imagesToBeImported.remove(currentCheckBox.getText());

This tries to remove a String(getText() prompted me to say String here) named aix71b from the Collection imagesToBeImported but the Collection imagesToBeImported contains elements of type ResourceListObject.

That is why nothing is getting removed from your Collection as String and ResourceListObject are not of the same type.

Edit:- (You can delete from the list using the below 2 ways)

You can traverse the imagesToBeImported(using an iterator) for each element of imagesToBeImportedCheckBox and remove the elements from imagesToBeImported whenever resourceListObjectElement.getName() equals currentCheckBox.getText().

Or else, you could override the equals method in your ResourceListObject based on the name field in it, so that you can do something like this to remove it from your imagesToBeImported.

imagesToBeImported.remove(new ResourceListObject(currentCheckBox.getText()));
// You need to add another constructor in your ResourceListObject class which takes in only the name field as the parameter.

Upvotes: 5

Maxim Efimov
Maxim Efimov

Reputation: 2737

The problem is that currentCheckBox.getText() and currentImage.getName() are not exactly the same objects - equals method is not true for them, even if the values are the same.

Upvotes: 0

Related Questions