This is not the most elegant way, but gives the idea how i decided to solve it. I loop through arraylist until condition comes true, then remove object from arraylist with correct reference.
import java.util.*;
public class MyArrayList2 {
public static class Person {
private String name;
private int id;
public Person(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return this.name;
}
public String toString() {
return name;
}
}
public static void main(String[] args) {
// Create a list from class Person
ArrayList<Person> henkilot = new ArrayList<Person>();
// Adding few Persons to list
henkilot.add(new Person("Maija", henkilot.size() + 1));
henkilot.add(new Person("Pekka", henkilot.size() + 1));
henkilot.add(new Person("Marko", henkilot.size() + 1));
henkilot.add(new Person("Pekka", henkilot.size() + 1));
henkilot.add(new Person("Pekka", henkilot.size() + 1));
// Printing out the original list
System.out.println(henkilot.toString());
// removing first occurance of pekka
for(Person name: henkilot) {
if(name.toString().equals("Pekka")) {
//System.out.println("Pekka löytys");
System.out.println(henkilot.remove(name));
break;
}
}
// Printing out the modified list
System.out.println(henkilot.toString());
}
}