Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
This method finds all Alien objects in the AlienList object’s Vector whose humanoid field has the value false. It stores all matching Alien objects in a new Vector that is then returned from the method. The method must also remove all the matching Alien objects from the Vector of AlienList. If there are no matching Alien objects then an empty Vector must be returned.

The only problem with my method is that when i call the method for a second time, the same two (removed) non humanoids which were returned in the first method call, are actually in this list returned by the 2nd call. Which they should have not been because they were removed on the previous call.

Here is my class with the method i need help with at the bottom:

What I have tried:

Java
<pre>public class AlientList
{
    // instance variables - replace the example below with your own
    private Vector<Alien> aliens;
    private Vector<Alien> nonHumanoids;

    /**
     * Constructor for objects of class AlientList
     */
    public AlientList()
    {
        aliens = new Vector<>();
        nonHumanoids = new Vector<>();
    }

    public void addAlien(Alien alien)
    {
        aliens.add(alien);
    }

    public void printHumanoids()
    {
        for(Alien alien: aliens) { 
            if(alien.getHumanoid() == true){    
                System.out.println(alien.getDetails());
            }
        }
    }

    public Vector<Alien> getNonHumanoids()
    {
        Iterator<Alien> it = aliens.iterator();
        while(it.hasNext()){
            Alien alien = it.next();
            if(alien.getHumanoid() == false){
                it.remove();
                nonHumanoids.add(alien);
            }
        }
        return nonHumanoids; 
    }
}
Posted
Updated 7-Dec-22 2:14am
Comments
Richard MacCutchan 7-Dec-22 9:12am    
You must be doing something elsewhere in your code to get the wrong results. I have just tried it and it successfully removes the unwanted entries and they are removed permanently.

1 solution

This is the same question you posted 3 days ago: I need this method to return an empty vector if there are no matching alien objects[^]

Please do not repost questions, it doesn't improve the chances of you getting an answer, it just wastes the time of volunteers, and that annoys people. Annoyed people are less likely to help you that happy ones ...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900