user5864910
user5864910

Reputation:

remove an object from an ArrayList

New to java here and just cannot get my head around arrays. I need to remove an item from an ArrayList, I'm lost on how to actually code this. My program reads a .csv file, passes from the main class to a second class a string, once in that second class I need to search the array list and remove that string if it is found and returns true saying it was removed. Any help is appreciated.

Second class

public class PersonLogImpl {

private boolean remove;
private boolean isLicenseUnique;
private boolean add;
private final ArrayList<Person> person;

public PersonLogImpl() {
    this.person = new ArrayList<>();
}


public ArrayList<Person> getPersonLog(){
    return Person;
}

public boolean add(Person obj){  //add person object to ordered list 
   person.add(obj);

   return add;
}

public boolean remove (String license){ //remove person with specific license from list

    if(person.remove(person.equals(add))){
            remove = true;
    }
   return remove;
}

EDIT: Person Class

public class Person{
private String licenseNumber;

public Person(){

}

public Person(String licenseNumber){
    this.licenseNumber = licenseNumber;
}

public String getLicenseNumber(){
    return licenseNumber;
}

public void setLicenseNumber(String licenseNumber){
    this.licenseNumber = licenseNumber;
}

@Override
public int hashCode(){
    int hash = 7;
    return hash;
}

@Override
public boolean equals(Object obj){
    if (this == obj){
        return true;
    }
    if (obj == null){
        return false;
    }
    if (getClass() != obj.getClass()){
        return false;
    }
    final Person other = (Person) obj;
    if (!Objects.equals(this.licenseNumber, other.licenseNumber)){
        return false;
    }
    return true;
}

@Override
public String toString(){
    return "Person{" + "licenseNumber=" + licenseNumber + '}';
}

public boolean validateLicense(){
    boolean retValue = false;
    if ((this.licenseNumber.matches("^[a-zA-Z]{2}\\d{7}$")))
        retValue = true;
    return retValue;
}

Upvotes: 0

Views: 891

Answers (4)

Vinicius Victor
Vinicius Victor

Reputation: 358

If you don't have one yet, create a method getLicense() on your Person class. That method should return the Person's license and then you can use the remove method below;

EDIT: I see now that you have a getLicenseNumber() method on your Person class.

public boolean remove(String license) {
   for (Person individual : person) { // go through each Person on the ArrayList
       if (individual.getLicenseNumber().equals(license)) // check if that Person's license is equal to the license we're looking for
           return person.remove(individual); // if so, remove that person and return true (remove will return true if the element is found)
   }

   return false; // if we never removed any element we never found a person with that license. In that case, return false
}

I'm assuming that each person has an unique license number and that you won't add the same Person twice to the ArrayList (or will stop the user from trying to). If your wish is to remove any occurrence of a Person with that license, you could use the following method:

public boolean remove(String license) {
    int listsize = person.size(); // size before removing any
    for(int i=0; i<person.size(); i++) {
        if (person.get(i).getLicenseNumber().equals(license))
            person.remove(i--); // i-- is required because the list size will change if we remove from it, so we need to decrement i
    }

    return !(listsize == person.size()); // if the size before is equal to the size now, we never removed any and thus return false
}

If you want a more simple solution, you could look into the method removeAll from ArrayList class

Upvotes: 0

Maciej Kowalski
Maciej Kowalski

Reputation: 26522

Try this:

public boolean remove (String license){ //remove person with specific license from list
    Iterator<Person> personIterator = person.iterator();
    boolean remove = false;

    while(personIterator.hasNext(){
        Person personInstance = personIterator.next();  
        if(personInstance.getLicense().equals(license))){
            personIterator.remove();
            remove = true;
            break;
        }
    }

   return remove;
}

Upvotes: 1

Jonny Henly
Jonny Henly

Reputation: 4213

You have a few errors in your code, I've highlighted them with comments below:

public class PersonLogImpl {
    private boolean remove;
    private boolean isLicenseUnique;
    private boolean add;
    private final ArrayList<Person> person;

    public PersonLogImpl() {
        // YOU SHOULD ALSO ASSIGN THE PRIVATE BOOLEANS HERE
        this.person = new ArrayList<>();
    }

    public ArrayList<Person> getPersonLog() {

        return Person; // What's going on here?
        // You're returning the actual Person class when you should be returning
        // an ArrayList of type Person (I think you meant for the P to be lowercase)
    }

    public boolean add(Person obj){  //add person object to ordered list 
       person.add(obj);

       return add; // You never assign true or false to 'add' (I believe 
       // it defaults to true) so this method will always return true (maybe 
       // false, not sure). you should instead use 'return person.add(obj);'
    }

    public boolean remove (String license){ //remove person with specific license from list

        // The code below makes no sense (no offence).
        if(person.remove(person.equals(add))){
                remove = true;
        }
       return remove;

        // Since I don't know the make up of the 'Person' class I can't 
        // tell you how this method should function. I'll make a guess though:
       for(int i = 0; i < person.size(); ++i) {
           if(person.get(i).getLicenseNumber().equals(license)) {
               return person.remove(i);
           }
       }

       // OR a shorter alternative
       return person.remove(new Person(license));
    }

}

Upvotes: 0

Lew Bloch
Lew Bloch

Reputation: 3433

@Newb2Java, The equals method can compare, in this case person with any object, but if the argument (add here) is a different type from that of the invoker (person), the result is false. Though you used a singular noun person, its type is plural, a collection of Persons. An ArrayList<Person> will never equal a Boolean (nor a boolean). The List method add will return true. remove will return true if it actually removed the argument, which must be of type Person. First, you have to find which element in the list has the indicated attribute value. So you have to iterate through the list, using an iterator being the best way, until you find each instance of an element with the given License. Something like this:

package practice;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class Personator {
  private final List<Person> persons = new ArrayList<>();

  public List<Person> getPersons() {
    return new ArrayList<>(persons);
  }

  public boolean add(Person person) {
    return persons.add(person);
  }

  public boolean remove(String license) {
    return remove(new Person(license));
  }

  public boolean remove(Person removal) {
    boolean wasRemoved = false;
    for (ListIterator<Person> iterator = persons.listIterator(persons.size());
       iterator.hasPrevious();
       ) {
      final Person person = iterator.previous();
      if (removal.equals(person)) {
        iterator.remove();
        wasRemoved = true;
      }
    }
    return wasRemoved;
  }
}

with this:

public class Person {
  private final String license;

  public Person(String license) {
    if (license == null) {
      throw new IllegalArgumentException("null license not allowed");
    }
    this.license = license;
  }

  public String getLicense() {
    return license;
  }

  @Override
  public String toString() {
    return "Person " + getLicense();
  }

  @Override
  public int hashCode() {
    return getLicense().hashCode();
  }

  @Override public boolean equals(Object oth) {
    if (this == oth) {
      return true;
    }
    if (! (oth instanceof Person)) {
      return false;
    }
    Person other = (Person) oth;
    return this.getLicense().equals(other.getLicense());
  }
}

Upvotes: 0

Related Questions