Using comparator interface to sort localdate - java

I am trying to sort a list of employees based on their date of joining.
Below is my employee class.
import java.time.LocalDate;
public class Employee {
private String name;
private String empID;
private Designation designation;
private LocalDate dateOfJoining;
private int monthlySalary;
public Employee(String name, String empID, Designation designation, LocalDate dateOfJoining, int monthlySalary) {
super();
this.name = name;
this.empID = empID;
this.designation = designation;
this.dateOfJoining = dateOfJoining;
this.monthlySalary = monthlySalary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmpID() {
return empID;
}
public void setEmpID(String empID) {
this.empID = empID;
}
public Designation getDesignation() {
return designation;
}
public void setDesignation(Designation designation) {
this.designation = designation;
}
public LocalDate getDOJ() {
return dateOfJoining;
}
public void setDOJ(LocalDate dOJ) {
dateOfJoining = dOJ;
}
public int getMonthlySalary() {
return monthlySalary;
}
public void setMonthlySalary(int monthlySalary) {
this.monthlySalary = monthlySalary;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dateOfJoining == null) ? 0 : dateOfJoining.hashCode());
result = prime * result + ((designation == null) ? 0 : designation.hashCode());
result = prime * result + ((empID == null) ? 0 : empID.hashCode());
result = prime * result + monthlySalary;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (dateOfJoining == null) {
if (other.dateOfJoining != null)
return false;
} else if (!dateOfJoining.equals(other.dateOfJoining))
return false;
if (designation == null) {
if (other.designation != null)
return false;
} else if (!designation.equals(other.designation))
return false;
if (empID == null) {
if (other.empID != null)
return false;
} else if (!empID.equals(other.empID))
return false;
if (monthlySalary != other.monthlySalary)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
#Override
public String toString() {
return "Employee [name=" + name + ", empID=" + empID + ", designation=" + designation + ", DOJ=" + dateOfJoining
+ ", monthlySalary=" + monthlySalary + "]";
}
}
And below is my Comparator class:
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Employecomparable {
public static void main(String[] args) {
List<Employee> listofemployee = new ArrayList<>();
LocalDate date1 = LocalDate.parse("2018-09-06");
LocalDate date2= LocalDate.of(2011, 12, 12);
listofemployee.add(new Employee("abc", "12345", Designation.ASE,LocalDate.of(2014, 2, 15) , 20000));
listofemployee.add(new Employee("abcd", "24680", Designation.SE, date1, 30000));
listofemployee.add(new Employee("abcde", "13570", Designation.SSE, LocalDate.of(2013, 05, 30), 40000));
listofemployee.add(new Employee("abcdef", "13690", Designation.TL, date2, 60000));
listofemployee.add(new Employee("xyz", "10909", Designation.AM, LocalDate.parse("20/03/2000"), 800000));
listofemployee.add(new Employee("koool", "89076", Designation.M, LocalDate.parse("31/01/2011"), 2000));
Collections.sort(listofemployee, new Comparator<Employee>() {
#Override
public int compare(Employee emp1, Employee emp2) {
if (emp1.getMonthlySalary() > emp2.getMonthlySalary())
return -1;
else if (emp1.getMonthlySalary() < emp2.getMonthlySalary())
return +1;
else
return 0;
}
});
System.out.println(listofemployee);
Collections.sort(listofemployee, new Comparator<Employee>(){
#Override
public int compare(Employee emp1, Employee emp2) {
if(emp1.getDOJ()>emp2.getDOJ())
return +1;
return 0;
}
});
But while trying to sort the list of employees based on their DOJ, I am getting error "The operator > is undefined for the argument type(s) java.time.LocalDate, java.time.LocalDate".
Can someone please help me on this?

dateOfJoining is a LocalDate which you cannot compare by >, < or ==. Java only supports those mathematical symbols on primitives (and their object representations). Instead you can use the methods .isBefore() or .isAfter(), see here.
Example:
Collections.sort(listofemployee, new Comparator<Employee>(){
#Override
public int compare(Employee emp1, Employee emp2) {
if(emp1.getDOJ().isBefore(emp2.getDOJ()))
return +1;
else if (emp1.getDOJ().isAfter(emp2.getDOJ)))
return -1
else
return 0;
}
});
Alternatively:
Collections.sort(listofemployee, new Comparator<Employee>(){
#Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getDOJ().compareTo(emp2.getDOJ);
}
});

Related

can arguments from a class that has objects passed to it work as a valid class to encapsulate the arguments in a method?

so i need to make a method to Rent a specific car to a specific customer in a specific
date. and that the car won't be rented at the same time more than once. this is what i cam up with. here are the exact words.
ClassRentalCompany (Main operations)
Attributes:
o static list of cars: ArrayList
(multi-aggregation from Car class)
o static list of transactions: ArrayList
(multi-aggregation from RentTransaction class)
static methods:
o Buying a new car and adding it to the application: takes
one argument (Car car): must ensure that the car has not
been added before.
o Renting a specific car to a specific customer in a specific
date: takes three arguments (Car car, Customer
customer, RentDate date): must ensure that the same car
won’t be rented twice in the same day
public boolean carRental(RentTransactions newTransaction) {
boolean carRented = false;
if (!carList.isEmpty()) {
for (RentalCars car : carList) {
//my problem is with the .rentDate.UCI
if (car.rentDate.equals(newTransaction.rentdate) && car.UCI == newTransaction.UCI) {
carRented = true;
break;
}
}
}
return carRented;
}
the .rentDate, UCI(unique customer ID) comes from the passed objects in RentTransactions class. the actual classes for date, car and customer are these classes...
public class DateOfRenting {
private int day;
private int month;
private int year;
public DateOfRenting(){
this(0, 0, 0);
}
public DateOfRenting(int day, int month, int year){
this.day = day;
this.month=month;
this.year=year;
}
public int getday() {
return day;
}
public void setday(int day) {
this.day=day;
}
public int getmonth() {
return month;
}
public void setmonth(int month) {
this.month=month;
}
public int getyear() {
return year;
}
public void setyear(int year) {
this.year=year;
}
#Override
public String toString()
{
return day+"/"+month+"/"+year;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass()){
return false;
}
DateOfRenting other = (DateOfRenting) obj;
return this.day == other.day && this.month == other.month &&
this.year == other.year;
}
}
import java.io.*;
import java.util.*;
public class Customers {
private final int UCI;
private String Name;
private int age;
private String gender;
public Customers(){
this(0, null, 0, null);
}
public Customers(int UCI, String Name, int age, String gender){
this.UCI = UCI;
this.Name=Name;
this.age=age;
this.gender=gender;
}
public int getUCI() {
return UCI;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name=Name;
}
public int getage() {
return age;
}
public void setage(int age) {
this.age=age;
}
public String getgender() {
return gender;
}
public void setbrandname(String gender) {
this.gender=gender;
}
#Override
public String toString()
{
return "the Unique civil ID is "+UCI+"the customer name is "+Name+
"the age of the customer is "+age+"the gender of the customer is "+
gender;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
if (!super.equals(obj)) {
return false;
}
Customers other = (Customers) obj;
return Objects.equals(UCI, other.UCI);
}
}
import java.io.*;
import java.util.*;
public class RentalCars implements Comparable<RentalCars> {
private final String UNP;
private String brandName;
private double rental_Rates;
private int wheel_Drive;
private String color;
private int milage;
public RentalCars(){
this(null,null, 0.0, 0, null, 0);
}
public RentalCars(String UNP, String brandName, double rental_Rates, int wheel_Drive,
String color, int milage){
this.UNP = UNP;
this.brandName=brandName;
this.rental_Rates=rental_Rates;
this.wheel_Drive=wheel_Drive;
this.color=color;
this.milage=milage;
}
public String getUNP() {
return UNP;
}
public String getbrandName() {
return brandName;
}
public void setbrandname(String brandName) {
this.brandName=brandName;
}
public double getrental_Rates() {
return rental_Rates;
}
public void setrental_Rates(double rental_Rates) {
this.rental_Rates=rental_Rates;
}
public int getwheel_Drive() {
return wheel_Drive;
}
public void setwheel_Drive(int wheel_Drive) {
this.wheel_Drive=wheel_Drive;
}
public String getcolor() {
return color;
}
public void setcolor(String color) {
this.color=color;
}
public int getmilage() {
return milage;
}
public void setmilage(int milage) {
this.milage=milage;
}
#Override
public String toString()
{
return "the Number Plate of the car is "+UNP+"the Car brand is "+brandName+
"the rent rate of this car is "+rental_Rates+"the wheel drive is "+
wheel_Drive+"the color of the car is "+color+"the milage is "+milage;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
if (!super.equals(obj)) {
return false;
}
RentalCars other = (RentalCars) obj;
return Objects.equals(UNP, other.UNP);
}
public int compareTo(RentalCars rc){
return UNP.compareTo(rc.UNP);
}
}
and the class RentTransactions is this...
public class RentTransactions {
RentalCars car;
Customers customer;
DateOfRenting rentDate;
public RentTransactions(){
}
public RentTransactions(RentalCars car, Customers customer, DateOfRenting rentDate){
this.car = car;
this.customer=customer;
this.rentDate=rentDate;
}
public RentalCars getcar() {
return car;
}
public void setcar(RentalCars car) {
this.car = car;
}
public Customers getcustomer() {
return customer;
}
public void setcustomer(Customers customer) {
this.customer = customer;
}
public DateOfRenting getrentDate() {
return rentDate;
}
public void setcar(DateOfRenting rentDate) {
this.rentDate = rentDate;
}
#Override
public String toString()
{
return car+"/"+customer+"/"+rentDate;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass()){
return false;
}
RentTransactions other = (RentTransactions) obj;
return this.car == other.car && this.rentDate == other.rentDate;
}
}
while the main operations method is this...
import java.util.*;
public class RentalCompany {
public static final List<RentalCars> carList = new ArrayList<>();
public static final List<RentTransactions> transactionList = new ArrayList<>();
public RentalCompany() {
}
public static List<RentalCars> getCar() {
return carList;
}
public static List<RentTransactions> getTransaction() {
return transactionList;
}
public static void buyCar(RentalCars car) {
carList.add(car);
}
public static void buycarcheck(String UNP) {
carList.stream().filter(car -> (car.getUNP().equals(UNP))).forEachOrdered(car -> {
carList.remove(car);
});
}
public boolean carRental(RentTransactions newTransaction) {
boolean carRented = false;
if (!carList.isEmpty()) {
for (RentalCars car : carList) {
//my problem is with the .rentDate.UCI
if (car.rentDate.equals(newTransaction.rentdate) && car.UCI == newTransaction.UCI) {
carRented = true;
break;
}
}
}
return carRented;
}
}
you say what i tried and what i expected is for the attributes to be passed

How to create own Custom Predicate to compare composite id in hazelcast

I want to create my own custome predicate to compare composite id's inside object. The need is to because i have to write specific date comparison logic on object inside object (composite id). I don't want to compare individual attributes.i want to use composite id because it comes from invoker and I can't get result using Predicate.in and Predicate.equals
My Object structure is like below
Birth{id=BirthId{name='b3', dob=Wed Jan 01 10:53:20 IST 1902}, name='b3', dob=Wed Jan 01 10:53:20 IST 1902, description='MNP'}
and inside IMap it is stored like below
key : BirthId{name='b3', dob=Wed Jan 01 10:53:20 IST 1902}
value : Birth{id=BirthId{name='b3', dob=Wed Jan 01 10:53:20 IST 1902}, name='b3', dob=Wed Jan 01 10:53:20 IST 1902, description='MNP'}
My Java Classes(Birth and Birthid) Structure is below
public class Birth implements Serializable, Portable {
private static final long serialVersionUID = 1L;
private BirthId id;
private String name;
private Date dob;
private String description;
public BirthId getId() {
return id;
}
public void setId(BirthId id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public int hashCode() {
return (new HashCodeBuilder()).append(this.id).append(this.name).append(this.dob).toHashCode();
}
public boolean equals(Object other) {
if (other == this) {
return true;
} else if (!(other instanceof Birth)) {
return false;
} else {
Birth rhs = (Birth) other;
return (new EqualsBuilder()).append(this.id, rhs.id).append(this.name, rhs.name).append(this.dob, rhs.dob).isEquals();
}
}
#Override public String toString() {
return "Birth{" + "id=" + id + ", name='" + name + '\'' + ", dob=" + dob + ", description='" + description + '\'' + '}';
}
public int getFactoryId() {
return 1;
}
public int getClassId() {
return 1;
}
public void writePortable(PortableWriter portableWriter) throws IOException {
portableWriter.writePortable("idComposite", getId());
portableWriter.writeUTF("id", getId().toString());
portableWriter.writeUTF("name", getName());
portableWriter.writeUTF("description", getDescription());
Date date = getDob();
portableWriter.writeLong("dob", ((date == null) ? -1 : date.getTime()));
}
public void readPortable(PortableReader portableReader) throws IOException {
setId((BirthId) portableReader.readPortable("idComposite"));
setName(portableReader.readUTF("name"));
setDescription(portableReader.readUTF("description"));
long date = portableReader.readLong("dob");
setDob(((date == -1) ? null : new Date(date)));
}
}
public class BirthId implements Comparable<BirthId>, Serializable, Portable {
private static final long serialVersionUID = 1L;
private String name;
private Date dob;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public int hashCode() {
return (new HashCodeBuilder()).append(this.name).append(this.dob).toHashCode();
}
public boolean equals(Object other) {
if (other == this) {
return true;
} else if (!(other instanceof BirthId)) {
return false;
} else {
BirthId rhs = (BirthId) other;
return (new EqualsBuilder()).append(this.name, rhs.name).append(this.dob, rhs.dob).isEquals();
}
}
public int compareTo(BirthId rhs) {
return this == rhs ? 0 : (null == rhs ? -1 : (new CompareToBuilder()).append(this.name, rhs.name).append(this.dob, rhs.dob).toComparison());
}
#Override public String toString() {
return "BirthId{" + "name='" + name + '\'' + ", dob=" + dob + '}';
}
public int getFactoryId() {
return 1;
}
public int getClassId() {
return 2;
}
public void writePortable(PortableWriter portableWriter) throws IOException {
portableWriter.writeUTF("name", getName());
Date date = getDob();
portableWriter.writeLong("dob", ((date == null) ? -1 : date.getTime()));
}
public void readPortable(PortableReader portableReader) throws IOException {
setName(portableReader.readUTF("name"));
long date = portableReader.readLong("dob");
setDob(((date == -1) ? null : new Date(date)));
}
public static ClassDefinition getClassDefinition(int portableVersion) {
ClassDefinitionBuilder result = new ClassDefinitionBuilder(1, 2, portableVersion);
result.addUTFField("name");
result.addLongField("dob");
return result.build();
}
}
I have created own custom Predicate to compare dates like below
public class DatePredicate extends AbstractPredicate<Comparable, BirthId> {
Comparable[] values;
private volatile Set<Comparable> convertedInValues;
public DatePredicate() {
}
public DatePredicate(String attribute, Comparable... values) {
if (values == null) {
throw new NullPointerException("Array can't be null");
} else {
this.values = values;
}
}
protected boolean applyForSingleAttributeValue(Map.Entry entry, Comparable attributeValue) {
//My own date comparison logic
return true;
}
public int getId() {
return 99;
}
}
Caller code is
Predicate p = new DatePredicate("id", new BirthId("12345",passSpecifiedDate()));
Result res = imap.values(p);
I am getting below error
Exception in thread "main" com.hazelcast.nio.serialization.HazelcastSerializationException: com.hazelcast.internal.serialization.impl.ArrayDataSerializableFactory#5f007be3 is not be able to create an instance for id: 99 on factoryId: -32
I do not know the best way to create own custom predicate and hazelcast doc does not specify the also.
Could any please guide me how to do this?
#oomph-fortuity, your DatePredicate extends AbstractPredicate which implements IdentifiedDataSerializable and used by built-in Hazelcast predicates. Built-in Predicate Serializable Factory try to deserialize your class & fails since it only knows how to serialize/deserialize built-in Predicates.
Instead, just implement com.hazelcast.query.Predicate interface:
class DatePredicate implements Predicate<BirthId, Birth> {
BirthId birthIdToCompare;
public DatePredicate() {
}
public DatePredicate(BirthId birthId) {
this.birthIdToCompare = birthId;
}
#Override
public boolean apply(Map.Entry<BirthId, Birth> mapEntry) {
BirthId key = mapEntry.getKey();
///your custom logic
return true;
}
}
And call like this
Predicate p = new DatePredicate(new BirthId("12345",passSpecifiedDate()));
Result res = imap.values(p);
Let me know if that works.

Creating immutable view of object using Proxy classes

I'm newest at using Proxy classes. I need to create fabric method of immutable view for my object (MusicalInstrument.class)
View must throw an Exception when i'm trying to invoke setter and invoking of other methods must transfer to my object.
Maybe you have got some examples or sources where i can find answers! Thanx!
public class MusicalInstrument implements Serializable {
/**
* ID of instrument.
*/
private int idInstrument;
/**
* Price of instrument.
*/
private double price;
/**
* Name of instrument.
*/
private String name;
public MusicalInstrument() {
}
public MusicalInstrument(int idInstrument, double price, String name) {
this.idInstrument = idInstrument;
this.price = price;
this.name = name;
}
public int getIdInstrument() {
return idInstrument;
}
public void setIdInstrument(int idInstrument) {
this.idInstrument = idInstrument;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MusicalInstrument that = (MusicalInstrument) o;
if (idInstrument != that.idInstrument) return false;
if (Double.compare(that.price, price) != 0) return false;
return name != null ? name.equals(that.name) : that.name == null;
}
#Override
public int hashCode() {
int result;
long temp;
result = idInstrument;
temp = Double.doubleToLongBits(price);
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "MusicalInstrument{" +
"idInstrument=" + idInstrument +
", price=" + price +
", name='" + name + '\'' +
'}';
}
You can use ImmutableProxy of the reflection-util library.
Example:
MusicalInstrument instrument = new MusicalInstrument(1, 12.5, "Guitar");
MusicalInstrument immutableView = ImmutableProxy.create(instrument);
assertThat(immutableView.getName()).isEqualTo("Guitar");
// throws UnsupportedOperationException
immutableView.setName(…);

Canteen with uniqe courses

I have a Canteen class and a Course class (and a BaseEntity). The Canteen class has a set of courses. A course is unique if the composition of name, dateOfServing and the canteen id is unique. I tried to write a test case which should throw an exception if a non-unique course is added to a canteen. But the test doesn't throw any exception at all. Which leads me to believe that I'm doing me Canteen and Course class wrong. The test in question is addDuplicatedCourseToCanteenTest. Anyone got a clue about what I'm doing wrong?
I'm new to TDD as well so any critique in that area is very welcome as well.
BaseEntity.java
#MappedSuperclass
public class BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
long id;
private Date createdAt;
private Date updatedAt;
// TODO: http://stackoverflow.com/a/11174297/672009
// Using the above we wouldn't have to created a CommentRepository
// Is that a good idea?
/**
* http://www.devsniper.com/base-entity-class-in-jpa/
*/
/**
* Sets createdAt before insert
*/
#PrePersist
public void setCreationDate() {
this.setCreatedAt(new Date());
}
/**
* Sets updatedAt before update
*/
#PreUpdate
public void setChangeDate() {
this.setUpdatedAt(new Date());
}
public Date getCreatedAt() {
return createdAt;
}
protected void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
protected void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BaseEntity other = (BaseEntity) obj;
if (id != other.id)
return false;
return true;
}
}
Canteen.java
#Entity
public class Canteen extends BaseEntity {
private String name;
// TODO: https://schuchert.wikispaces.com/JPA+Tutorial+1+-+Embedded+Entity
// http://docs.oracle.com/javaee/6/api/javax/xml/registry/infomodel/PostalAddress.html
//private Address address;
//private PostalAddress postalAddress;
/**
* In honor of KISS I simply use a simple string address as a holder for the restaurants address.
* The idea is that the string will contain an address which will be valid according to google maps.
* Same goes for openingHours, phoneNumber and homepage... KISS wise.
*/
private String address;
private String openingHours; // A string which will be presented within a pre tag
// Eg. <pre>Mandag - Torsdag 10-22
// Fredag - Lørdag 10-24
// Søndag 11-20</pre>
private String contact;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Course> courses = new HashSet<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getOpeningHours() {
return openingHours;
}
public void setOpeningHours(String openingHours) {
this.openingHours = openingHours;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
public boolean addCourse(Course course)
{
return getCourses().add(course);
}
#Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Canteen other = (Canteen) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
Course.java
#Entity
public class Course extends BaseEntity {
private String name;
private Date dateOfServing;
#ManyToOne
private Canteen canteen;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDateOfServing() {
return dateOfServing;
}
public void setDateOfServing(Date dateOfServing) {
this.dateOfServing = dateOfServing;
}
public Canteen getCanteen() {
return canteen;
}
public void setCanteen(Canteen canteen) {
this.canteen = canteen;
}
#Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((canteen == null) ? 0 : canteen.hashCode());
result = prime * result
+ ((dateOfServing == null) ? 0 : dateOfServing.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Course other = (Course) obj;
if (canteen == null) {
if (other.canteen != null)
return false;
} else if (!canteen.equals(other.canteen))
return false;
if (dateOfServing == null) {
if (other.dateOfServing != null)
return false;
} else if (!dateOfServing.equals(other.dateOfServing))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
CanteenHasCoursesTest.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = PersistenceConfig.class)
public class CanteenHasCoursesTest {
#Autowired
private CanteenRepository canteenRepository;
private String canteenName;
private String courseName;
private Canteen canteen;
private Course course;
#Before
public void setUp() {
// Generate unique random name
canteenName = UUID.randomUUID().toString();
// Generate unique random name
courseName = UUID.randomUUID().toString();
// Create new canteen
canteen = new Canteen();
canteen.setName(canteenName);
// Create new course
course = new Course();
course.setName(courseName);
}
#Test
public void addCourseToCanteenTest() {
// Add course
canteen.addCourse(course);
// Save canteen
canteenRepository.save(canteen);
// Find it again
Canteen c = canteenRepository.findOne(canteen.getId());
// Confirm attributes are as expected
assertNotNull(c);
Set<Course> courses = c.getCourses();
Iterator<Course> it = courses.iterator();
assertTrue(it.hasNext());
Course course = it.next();
assertEquals(courseName, course.getName());
}
// TODO: expect some data violation exception
// #Test(expected = IndexOutOfBoundsException.class)
#Test
public void addDuplicatedCourseToCanteenTest() {
// Add course
canteen.addCourse(course);
// Add it again
canteen.addCourse(course);
// Save canteen
canteenRepository.save(canteen);
}
#After
public void tearDown() {
canteenRepository = null;
canteenName = null;
courseName = null;
canteen = null;
course = null;
}
}

Strange program behaviour

This elementary program is driving me up the wall.
There must be something very simple I don't see here.
WHY is the exception triggered?
There are 2 classes:
1)
public class Person
{
private String name;
private int age;
private static int numberOfPeople = 0;
public Person()
{
this("John Doe", 0);
numberOfPeople++;
}
public Person(String name, int age)
{
this.setAge(age);
this.setName(name);
numberOfPeople++;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public int getNumberOfPersons()
{
return numberOfPeople;
}
public String toString()
{
return this.name + " " + this.age;
}
}
2)
import java.util.Random;
public class Adult extends Person
{
private String number;
public static final int MIN_AGE = 18;
public Adult(String name, int age, String number)
{
super(name, 0);
this.setAge(age);
this.number = number;
}
public Adult(Adult adult)
{
this(adult.getName(), adult.getAge(), adult.getNumber());
}
public Adult()
{
this.number = "";
this.setAge(MIN_AGE);
Random rand = new Random();
int result = rand.nextInt(2);
if (result == 0)
{
this.setName("John Doe");
}
else
{
this.setName("Jane Doe");
}
}
public void setAge(int age)
{
if (age < MIN_AGE)
{
throw new IllegalArgumentException("The person must be 18 or older!");
}
else
{
super.setAge(MIN_AGE);
}
}
public String getNumber()
{
return this.number;
}
private void setNumber(String number)
{
this.number = number;
}
public String toString()
{
return this.getName() + " " + this.getNumber() + " " + this.getAge();
}
public boolean equals(Object obj)
{
boolean result = false;
if (obj != null && this.getClass() == obj.getClass())
{
Adult other = (Adult) obj;
if (this.getName().equals(other.getName()) &&
this.getNumber().equals(other.getNumber()) &&
this.getAge() == other.getAge())
{
result = true;
}
}
return result;
}
public static void main(String[] args)
{
Adult ad = new Adult();
System.out.println(ad);
}
}
This gives my the following error:
Exception in thread "main" java.lang.IllegalArgumentException: The person must be 18 or older!
at people.Adult.setAge(Adult.java:39)
at people.Person.<init>(Person.java:16)
at people.Adult.<init>(Adult.java:12)
at people.Adult.main(Adult.java:75)
Your Person() constructor creates another person. Since Adult extends Person, there is an implicit super() call which is likely the cause of your error.

Categories

Resources