How to prevent OutOfMemory Error before it occurs, and how to know if heap free space enough to add a new object to the list of objects. here is my code, I want this add method to return false if adding the new person object will cause OutOfMemory Error.
private static List<Person> persons;
public boolean add(String id, String name) {
boolean isExists = persons.stream().filter(p -> p.getId().equals(id)).findFirst().isPresent();
if (isExists == false){
Person person = new Person(id,name);
persons.add(person);
return true;
}
return false;
}
And this is person class:_
public class Person{
private String id;
private String name;
}