Skip to content

Instantly share code, notes, and snippets.

@dhinojosa
Last active November 10, 2021 21:43
Show Gist options
  • Save dhinojosa/021f8b0907ca30224499993cbf66b8e8 to your computer and use it in GitHub Desktop.
Save dhinojosa/021f8b0907ca30224499993cbf66b8e8 to your computer and use it in GitHub Desktop.
package com.xyzcorp;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
public class Person implements Comparable<Person>{
private String firstName;
private String middleName; //null by default
private String lastName;
private HashSet<String> interests;
//Constructor
public Person(String firstName, String lastName) {
Objects.requireNonNull(firstName);
Objects.requireNonNull(lastName);
if (firstName.isEmpty())
throw new IllegalArgumentException("First Name cannot be empty");
if (lastName.isEmpty())
throw new IllegalArgumentException("Last Name cannot be empty");
this.firstName = firstName;
this.lastName = lastName;
}
public Person(String firstName, String middleName, String lastName) {
this(firstName, lastName);
Objects.requireNonNull(middleName);
if (middleName.isEmpty())
throw new IllegalArgumentException("Middle Name cannot be empty");
this.middleName = middleName;
}
//You call these after the
//object has been constructed
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
public Optional<String> getMiddleName() {
return Optional.ofNullable(middleName);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(firstName, person.firstName)
&& Objects.equals(lastName, person.lastName);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
@Override
public String toString() {
return String.format("%s %s", firstName, lastName);
}
public void addInterest(String interest) {
interests.add(interest);
}
public Set<String> getInterests() {
return Set.copyOf(interests);
}
public int getNumberOfInterests() throws Exception {
return interests.size();
}
@Override
public int compareTo(Person other) {
return this.lastName.compareTo(other.lastName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment