In: Computer Science
(JAVA): The Collection ADT
1. We have a Circle class that includes radius attribute of type int, set by the constructor. Write a compareTo method for this class so that circle objects are ordered on the basis of their circumference (? = 2??).
2. We have a Person class that includes name and age attributes of type String and int respectively, both set by the constructor. Write a compareTo method for this class so that person objects are ordered on the basis of their name.
public class Circle implements Comparable<Circle> {
private int radius;
/**
* @param aRadius
*/
public Circle(int aRadius) {
super();
radius = aRadius;
}
/**
* @return the radius
*/
public int getRadius() {
return radius;
}
/**
* @param aRadius the radius to set
*/
public void setRadius(int aRadius) {
radius = aRadius;
}
@Override
public int compareTo(Circle c) {
//comparing the circumference of
the both the objects
return new
Double(getCircumference()).compareTo(c.getCircumference());
}
//returns the circumference of the circle using 2 PI R
formula
public double getCircumference() {
return 2 * Math.PI * radius;
}
}
Answer 2:
public class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String aName, int aAge) {
super();
name = aName;
age = aAge;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param aName the name to set
*/
public void setName(String aName) {
name = aName;
}
/**
* @param aAge the age to set
*/
public void setAge(int aAge) {
age = aAge;
}
@Override
public int compareTo(Person p) {
//comparing using the name so that
Person objects will ordered based on name
return
getName().compareTo(p.getName());
}
}
Note : Please comment below if you have concerns. I am here to help
you
If you like my answer please rate and help me it is very Imp for me