I have to order Appointments by date and time. I have an ArrayList of Appointments and have tried to create a comparator to compare their dates and times. I am trying to use the Collections.sort method, passing it the ArrayList of Appointments and the AppointmentComparator I have created. When compiling I get a "No suitable method for sort." Here's a link to the full error message generated by the compiler : http://prntscr.com/7y4qb
Comparator:
public class AppointmentComparator implements Comparator<Appointment>
{
public int compare(Appointment a, Appointment b)
{
if (a.getDay() < b.getDay())
return -1;
if (a.getDay() == b.getDay())
{
if (a.getStart() < b.getStart())
return -1;
if (a.getStart() > b.getStart())
return 1;
return 0;
}
return 1;
}
Line with syntax error:
Collections.sort(book, new AppointmentComparator());
variable book is an ArrayList of Appointments. ArrayList<Appointment>
AppointmentBook class:
import java.util.ArrayList;
import java.util.Collections;
public class AppointmentBook
{
private ArrayList<Appointment> book;
public AppointmentBook()
{
book = new ArrayList<Appointment>();
}
public void addAppointment(Appointment appt)
{
book.add(appt);
Collections.sort(book, new AppointmentComparator());
}
public String printAppointments(int day)
{
String list = "";
for (int i = 0; i < book.size(); i++)
{
if (book.get(i).getDay() == day)
{
list = list + "Appointment description: " + book.get(i).getDescription() + "\n" + "Date of Appointment: " +
book.get(i).getDay() + "\n" + "Time: " + book.get(i).getStart() + " - " + book.get(i).getEnd() + "\n" + "\n";
}
}
return list;
}
Appointment class:
public class Appointment
{
private String desc;
private int day; //in format mmddyyyy
private int start; //in format hhmm
private int end; //in format hhmm
public Appointment(String description, int aptDay, int startTime, int endTime)
{
desc = description;
day = aptDay;
start = startTime;
end = endTime;
}
public String getDescription()
{
return desc;
}
public int getDay()
{
return day;
}
public int getStart()
{
return start;
}
public int getEnd()
{
return end;
}
}
From the error message it looks like you forgot to declare your comparator as implementing the interface:
public class AppointmentComparator implements Comparator<Appointment> {}
It needs to have the implements part, not just contain the method.
You need to cast your new AppointmentComparator
Collections.sort(book, new (Comparator)AppointmentComparator());
Also we can use inner class for some cases:
public int indexOfLargest(ArrayList<QuakeEntry> Data) {
Comparator<QuakeEntry> cmtr = new Comparator<QuakeEntry>() {
#Override
public int compare(QuakeEntry t, QuakeEntry t1) {
if (t.getMagnitude() < t1.getMagnitude())
return -1;
if (t.getMagnitude() == t1.getMagnitude())
return 1;
if (t1.getMagnitude() > t1.getMagnitude())
return 0;
return 1;
}
};
QuakeEntry max = Collections.max(Data, cmtr);
int maxIndex = Data.indexOf(max);
//----------------------------------------------------------------------
System.out.println("//---------------------------------------------------");
System.out.println("ArrayList sorted by Magnitude using inner class with Comparator");
System.out.println("//---------------------------------------------------");
Collections.sort(Data, cmtr);
for (QuakeEntry qe : Data) {
System.out.println(qe);
}
return maxIndex;
}
code for all classes:
https://github.com/Evegen55/Java_DukeEdu_Coursera_2/blob/master/Earthquakes_Programming%20and%20Interfaces/src/earthquakes_programming_and_interfaces/QuakeEntry.java
Seems you have not implemented The comparator interface for your AppointmentComparator
Related
I'm writing a simple code to show various details about a person. I've used arrays to create name.
When I try to run my code the location/ directory for name comes out as [Ljava.lang.String;#1f32e575.
My code runs results are:
Name
ii
jj
[Ljava.lang.String;#1f32e575 // code to remove
My code:
public static String[] name() {
System.out.println("Name");
n = new String[]{ "ii", "jj" };
for (int i = 0; i < n2.length; i++) {
System.out.println(n[i]);
}
}
Here, is your fixed code:
import java.util.ArrayList;
class Detail {
private String name;
private String nationality;
private static String[] hobby2;
public Detail() {
}
public String getName() {
return name = "A";
}
public String getNationality() {
return nationality = "abc";
}
public void setInfo(String name, String nationality) {
this.name = name;
this.nationality = nationality;
}
public static void setHobbies() {
hobby2 = new String[] { "ii", "jj" };
System.out.println("Hobbies");
for (int i = 0; i < hobby2.length; i++) {
System.out.println("\t" + hobby2[i]);
}
}
public static void setWishes() {
System.out.println("Wishes");
ArrayList<String> allWishes = new ArrayList<String>();
allWishes.add("aa");
allWishes.add("bb");
allWishes.add("cc");
allWishes.add("dd");
for (String i : allWishes) {
System.out.println("\t" + i);
}
}
public void displayDetail() {
DOB d = new DOB();
System.out.println("Name: " + getName());
System.out.println("Nationality: " + getNationality());
System.out.println("Date of birth: " + d.dateString(1, "Jan", 1000));
setHobbies();
setWishes();
}
}
class DOB {
public String dateString(int day, String month, int year) {
String dob = (day + " " + month + ", " + year);
return (dob);
}
}
class Test {
public static void main(String[] args) {
MyInfo my = new MyInfo();
my.displayDetail();
}
}
The very first value you don't want was the object ID, you simply can't return the values of an object. If you want to see the values then you have to override the toString() method.
The second value was visible just because you returned the list. If you were using print() inside your method then there was no need to return it.
Tips: You need to get a better understanding of getter and setter methods because you have messed up the entire concept in your code. Your blank constructor is not needed. Rather, you should initialize all the fields (class variables of Detail class) in the constructor.
Remove System.out.println in displayDetail() method as below,
setHobbies();
setWishes();
I am a Java beginner and two questions boggle me really hard, so I have these questions.
For instance, I do not understand why in the Class Suitcase the method call getWeight() can be called, but in the Class Hold the method call totalWeight() not.
It works here:
public int totalWeight() {
int momentaryWeight = 0;
for (Item items: this.itemList) {
momentaryWeight = momentaryWeight + items.getWeight();
}
return momentaryWeight;
}
But not here:
public String toString() {
int momentaryWeight = 0;
int index = 0;
for (int i = index; i < this.suitcaseList.size(); i++) {
Suitcase suitcaseChosen = this.suitcaseList.get(i);
int weightOfsuitcaseChosen = suitcaseChosen.totalWeight();
momentaryWeight += weightOfsuitcaseChosen;
}
Also when having a method that returns something and using an if statement (so 2 return statements) it asks me afterwards for another return statement, like here:
public Item printGoods() {
if (this.itemList.isEmpty() == true) {
return null;
} else {
for (Item itemThis: this.itemList) {
return itemThis;
}
}
return null;
}
I know that maybe these are dull questions, but I couldn't think of a better forum to understand it.
Thanks.
The Hold class:
public class Hold {
private int maxWeight;
private ArrayList<Suitcase> suitcaseList;
public Hold(int maxWeightGiven) {
this.maxWeight = maxWeightGiven;
this.suitcaseList = new ArrayList<>();
}
public void addSuitcase(Suitcase suitcase) {
this.suitcaseList.add(suitcase);
}
public String toString() {
int momentaryWeight = 0;
int index = 0;
for (int i = index; i < this.suitcaseList.size(); i++) {
Suitcase suitcaseChosen = this.suitcaseList.get(i);
int weightOfsuitcaseChosen = suitcaseChosen.totalWeight();
momentaryWeight += weightOfsuitcaseChosen;
}
return this.suitcaseList.size() + " suitcases" + " (" + momentaryWeight + " kg)";
}
The Suitcase class:
import java.util.ArrayList;
public class Suitcase {
private int maximumWeight;
private ArrayList<Item> itemList;
public Suitcase(int maximumWeightGiven) {
this.maximumWeight = maximumWeightGiven;
this.itemList = new ArrayList<>();
}
public void addItem(Item item) {
int momentaryWeight = 0;
if (momentaryWeight <= this.maximumWeight && momentaryWeight + item.getWeight() <= this.maximumWeight) {
this.itemList.add(item);
}
}
public int totalWeight() {
int momentaryWeight = 0;
for (Item items: this.itemList) {
momentaryWeight = momentaryWeight + items.getWeight();
}
return momentaryWeight;
}
The class Item looks like this:
public class Item {
private String name;
private int weight;
public Item(String nameGiven, int weightGiven) {
this.name = nameGiven;
this.weight = weightGiven;
}
public String getName() {
return this.name;
}
public int getWeight() {
return this.weight;
}
public String toString() {
return this.name + "( " + this.weight + " kg)";
}
}
}
First question is incomplete code and detail.
Second question: suppose if-condition is false and your loop condition is also false(empty array) then the program will not reach to return statement that's why you have to add an extra return statement.
You can move last return line inside the else block
Don't know what happened, but as I worked on it a while later, suddenly the error messages disappeared and I was able to run the program. Is there a special key in NetBeans for "Refreshing"?
Alright I am stuck on how do I implement this binary search that will receive data from other classes.
I am trying to implement it in my own ADT.
I have implemented a List ADT manually but now I want to add in a search operation which utilizes binary search algorithm manually and doesn't uses any built in Java API.
Example this is my sorted list interface that I implemented manually.
public class SortedArrayList<T extends Comparable<T>> implements SortedListInterface<T>{
private boolean binarySearch(// What parameters should I receive from Student Object?) {
// This will be my binary search implementation
}
}
The problem is I will be creating a Student class where I will add the instances of the student class into the sortedArrayList above.
Like how am I going to receive the data to be put into the binary search algorithm in a generics typed sortedArrayList?
Do note I am not allowed to use any JAVA Built-IN API , everything must be implemented manually else I can finish this easily but its a pain now since its limited.
Example I want to binary search by Student name from Student's class. How will I need to implement and receive data into this manually implemented ADT of mine?
public class SortedArrayList<T extends Comparable<T>> implements SortedListInterface<T>{
private T[] list;
private boolean binarySearch(int first, int last, T desiredItem) {
int mid = (first + last) / 2;
if(desiredItem.getFullName().equals(list[mid])
// This part over here. How do I access attributes from Student class in this ADT so that I can access the data and do comparison for the binary search..
}
}
How do I access attributes from Student class into my own ADT so that I can do comparisons on binary search algorithm?!
I am literally stuck.
I would appreciate someone giving me directions.
I repeat again no BUILT-IN APIs from JAVA, implementation manually only
ADT SortedList Interface
public interface SortedListInterface <T extends Comparable<T>> {
public boolean add(T element);
public T get(int index);
public boolean search(T element);
public T remove(int index);
public void clear();
public int getLength();
public boolean isEmpty();
public boolean isFull();
}
ADT SortedList Implementation Code
public class SortedArrayList<T extends Comparable<T>> implements SortedListInterface<T>{
//Data Types
private T[] list;
private int length;
private static final int SIZE = 10;
// Constructors
public SortedArrayList() {
this(SIZE);
}
public SortedArrayList(int size) {
length = 0;
list = (T[]) new Comparable[SIZE]; // an array of instances of a class implementing Comparable interface and able to use compareto method but its overidden instead
}
// Setter & Getters
#Override
public int getLength() {
return length;
}
#Override
public boolean isEmpty() {
return length == 0;
}
#Override
public boolean isFull() {
return false;
}
#Override
public void clear() {
length = 0;
}
// Array Expansion
private boolean isArrayFull() {
return length == list.length;
}
private void expandArray() {
T[] oldList = list;
int oldSize = oldList.length;
list = (T[]) new Object[2 * oldSize];
for (int i = 0; i < oldSize; i++) // copy old array elements into new array elements
list[i] = oldList[i];
}
// ADT METHODs
// Add New Elements Function
#Override
public boolean add(T element) {
int i = 0;
while (i < length && element.compareTo(list[i]) > 0) // return 0 with equal , return more than 1 if element larger than list[i] , return -1 if less
i++;
makeRoom(i + 1);
list[i] = element;
length++;
return true;
}
private void makeRoom(int index) { // accepts given index
int newIndex = index - 1;
int lastIndex = length - 1;
for (int i = lastIndex; i >= newIndex; i--)
list[i + 1] = list[i];
}
//Remove Elements Function
#Override
public T remove(int index) { // accepts given index
T result = null;
if ( index >= 1 && index <= length ) {
result = list[index - 1];
if (index < length)
removeGap(index);
length--;
}
return result;
}
private void removeGap(int index) { // accepts given index and remove the gap where the element its removed
int removedIndex = index - 1;
int lastIndex = length - 1;
for (int i = removedIndex; i < lastIndex; i++)
list[i] = list[i + 1]; // shifts elements back to remove the gap
}
// Get Element
#Override
public T get(int index) { // accepts given index and return the object
T object = null;
if ( index >= 1 && index <= length)
object = list[index - 1];
return object;
}
// Search Algorithms
#Override
public boolean search(T element) {
return binarySearch(element);
}
private boolean binarySearch(// Implementation here) {
// Implementation here
}
//To String Method
#Override
public String toString() {
String result = "";
for (int i = 0; i < length; i++)
result += list[i] + "\n";
return result;
}
}
Student Class Implementation
public class Student implements Comparable<Student>{
// Data Types
private Name name;
private char gender;
private String icNo;
private String mobileNo;
private Course course;
private int group;
private String dOB;
// Constructors
public Student() {
}
public Student(Name name, char gender, String icNo, String mobileNo, Course course, int group, String dOB) {
this.name = name;
this.gender = gender;
this.icNo = icNo;
this.mobileNo = mobileNo;
this.course = course;
this.group = group;
this.dOB = dOB;
}
public Student(Name name) {
this.name = name;
}
// setter
public void setName(Name name) {
this.name = name;
}
public void setGender(char gender) {
this.gender = gender;
}
public void setIcNo(String icNo) {
this.icNo = icNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public void setCourse(Course course) {
this.course = course;
}
public void setGroup(int group) {
this.group = group;
}
public void setdOB(String dOB) {
this.dOB = dOB;
}
// getter
public Name getName() {
return name;
}
public char getGender() {
return gender;
}
public String getIcNo() {
return icNo;
}
public String getMobileNo() {
return mobileNo;
}
public Course getCourse() {
return course;
}
public int getGroup() {
return group;
}
public String getdOB() {
return dOB;
}
#Override
public String toString() {
return "Student{" + "name=" + name + ", gender=" + gender + ", icNo=" + icNo + ", mobileNo=" + mobileNo + ", course=" + course + ", group=" + group + ", dOB=" + dOB + '}';
}
public int compareTo(Student object) { // Sort according to name if name same then sort according to gender and so on.
int c = this.name.getFullName().compareTo(object.getName().getFullName());
if(c == 0)
c = this.gender - object.getGender();
if(c == 0)
c = this.icNo.compareTo(object.getIcNo());
if(c == 0)
c = this.mobileNo.compareTo(object.getMobileNo());
if(c == 0)
c = this.group - object.getGroup();
if(c == 0)
c = this.dOB.compareTo(object.getdOB());
return c;
}
}
Course Class
public class Course {
// Data Types
private String courseCode;
private String courseName;
private double courseFee;
// Constructors
public Course() {
}
public Course(String courseCode, String courseName, double courseFee) {
this.courseCode = courseCode;
this.courseName = courseName;
this.courseFee = courseFee;
}
// setter
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public void setCourseFee(double courseFee) {
this.courseFee = courseFee;
}
// getter
public String getCourseCode() {
return courseCode;
}
public String getCourseName() {
return courseName;
}
public double getCourseFee() {
return courseFee;
}
#Override
public String toString() {
return "CourseCode = " + courseCode + "Course Name = " + courseName + "Course Fee = " + courseFee;
}
}
Name Class
public class Name {
// Data Types
private String firstName;
private String lastName;
// Constructors
public Name() {
}
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// setter
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
// getter
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getFullName(){
return firstName + " " + lastName;
}
#Override
public String toString() {
return "Name{" + "firstName=" + firstName + ", lastName=" + lastName + '}';
}
The binary search algorithm relies on comparing a value being searched for with values in the list being searched. That's why the declaration of your class that implements the SortedListInterface is:
SortedArrayList<T extends Comparable<T>>
Note the extends Comparable<T>.
Comparable is an interface through which you can compare two objects. Hence in the search() method that you have to implement, you know that every object in the list defines the compareTo() method and you simply use that method to compare the object being searched for with individual objects in the list.
Here is a simple implementation of the binary search algorithm in the context of your project.
private T[] list; // The list to search.
private int count; // The number of non-null elements in 'list'.
public boolean search(T element) {
boolean found = false;
int lo = 0;
int hi = count - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list[mid].compareTo(element) < 0) {
lo = mid + 1;
}
else if (list[mid].compareTo(element) > 0) {
hi = mid - 1;
}
else {
found = true;
break;
}
}
return found;
}
With a method, you have a method parameter. In the method code you use the parameter name. But when you invoke that method from other code, you provide a value which is substituted for the parameter. In the same way, the code above uses a type parameter which is substituted with the name of an actual class when you create an instance of class SortedArrayList. In your case, T is substituted with Student and class Student must implement the compareTo() method. Hence method search(), in class SortedArrayList does not need to know about the members in class Student.
So you would first create an instance of SortedArrayList like this:
SortedArrayList<Student> theList = new SortedArrayList<>();
Then you can call the search() method like this:
Student s = new Student(/* relevant parameter values */);
theList.search(s);
EDIT
I understand that you don't necessarily want to search for a Student, you may want to search for the Name of a student or a student's mobile phone number. In that case I believe you need a Comparator. Here is the code for class SortedArrayList with the addition of a Comparator
import java.util.Comparator;
import java.util.Objects;
public class SortedArrayList<T extends Comparable<T>> implements SortedListInterface<T> {
private static final int SIZE = 10;
private Comparator<? super T> comparator;
private T[] list;
private int count;
#SuppressWarnings("unchecked")
public SortedArrayList(Comparator<? super T> c) {
comparator = c;
list = (T[]) new Comparable[SIZE]; // No way to verify that 'list' only contains instances of 'T'.
/* NOTE: Following is not allowed.
list = new T[SIZE]; // Cannot create a generic array of T
*/
}
#Override
public boolean add(T element) {
Objects.requireNonNull(element, "Cannot add null element.");
boolean result = false;
if (count == 0) {
list[0] = element;
count = 1;
result = true;
}
else {
if (!isFull()) {
int i = 0;
while (list[i] != null) {
if (element.compareTo(list[i]) < 0) {
break;
}
i++;
}
if (list[i] != null) {
for (int j = count - 1; j >= i; j--) {
list[j + 1] = list[j];
}
}
list[i] = element;
count++;
result = true;
}
}
return result;
}
#Override
public T get(int index) {
checkIndex(index);
return list[index];
}
#Override
public boolean search(T element) {
if (comparator == null) {
return binarySearchComparable(element);
}
else {
return binarySearchComparator(element);
}
}
#Override
public T remove(int index) {
checkIndex(index);
T removed = list[index];
list[index] = null;
for (int i = index; i < count; i++) {
list[i] = list[i + 1];
}
count--;
list[count] = null;
return removed;
}
#Override
public void clear() {
for (int i = 0; i < count; i++) {
list[i] = null;
}
count = 0;
}
#Override
public int getLength() {
return count;
}
#Override
public boolean isEmpty() {
return count == 0;
}
#Override
public boolean isFull() {
return count == SIZE;
}
private boolean binarySearchComparable(T element) {
boolean found = false;
int lo = 0;
int hi = count - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list[mid].compareTo(element) < 0) {
lo = mid + 1;
}
else if (list[mid].compareTo(element) > 0) {
hi = mid - 1;
}
else {
found = true;
break;
}
}
return found;
}
private boolean binarySearchComparator(T key) {
int low = 0;
int high = count - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
T midVal = list[mid];
int cmp = comparator.compare(midVal, key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return true; // key found
}
return false; // key not found.
}
private void checkIndex(int index) {
if (index < 0) {
throw new IllegalArgumentException("Negative index.");
}
if (index >= count) {
throw new IllegalArgumentException(String.format("Supplied index %d is not less than %d", index, count));
}
}
}
Here is an example Comparator for the Name of a Student
import java.util.Comparator;
public class NameComparator implements Comparator<Student> {
#Override
public int compare(Student student1, Student student2) {
int result;
if (student1 == null) {
if (student2 == null) {
result = 0;
}
else {
result = -1;
}
}
else {
if (student2 == null) {
result = 1;
}
else {
result = student1.getName().getFullName().compareTo(student2.getName().getFullName());
}
}
return result;
}
}
So in order to search the list according to any combination of Student attributes, simply implement an appropriate Comparator and pass it to the SortedArrayList class.
EDIT 2
Following your comments from November 17, 2019.
Below is code for a "name and mobile" Comparator. As I wrote in my previous Edit, you need to write an appropriate Comparator for a given combination of Student attributes.
import java.util.Comparator;
/**
* Compares {#code Student} name and mobile phone number.
*/
public class NameAndMobileComparator implements Comparator<Student> {
#Override
public int compare(Student student1, Student student2) {
int result;
if (student1 == null) {
if (student2 == null) {
result = 0;
}
else {
result = -1;
}
}
else {
if (student2 == null) {
result = 1;
}
else {
result = student1.getName().getFullName().compareTo(student2.getName().getFullName());
if (result == 0) {
result = student1.getMobileNo().compareTo(student2.getMobileNo());
}
}
}
return result;
}
}
My project involves 2 classes: Members & Society.
Currently I have written a method 'removeMembers()' in the Society Class that when given a particular month and year, it removes all the members who fit the description.
However, how would I create a separate collection class object which returns the deleted members?
Any help or advice on this will be appreciated, I will also post my code for both classes.
Society Class:
public class Society
{
private ArrayList<Member> myMembers;
private Member member;
private String societyName;
private boolean feesPaid;
public Society(String society)
{
myMembers = new ArrayList<Member>();
this.societyName = society;
}
public String getSocietyName()
{
return societyName;
}
public void join(Member member)
{
myMembers.add(member);
}
public void showMember(int listPosition)
{
Member member;
if( listPosition < myMembers.size() )
{
member = myMembers.get(listPosition);
System.out.println("Position " + listPosition + ": " + member);
}
}
public void joinedInMonth(int joined) {
if (joined > 12 || joined < 1) {
System.out.println("Invalid number. Please enter a number from 1 - 12.");
}
long joinedMonth = myMembers.stream().filter(m -> m.getMonth() == joined).count();
System.out.printf("%d members have joined this society on month %d%n", joinedMonth, joined);
}
public int numberOfMembers()
{
return myMembers.size();
}
public void printDetails()
{
for (Member m : myMembers) {
System.out.println("Society Name: " + societyName);
System.out.println(m.toString());
System.out.println("--------------------------");
}
}
public void removeMembers(int month, int year) {
myMembers.removeIf(m -> m.getYear() == year && m.getMonth() == month);
}
public void payFees(Member member)
{
if (member.isFeesPaid()) {
System.out.println("Fees has been paid");
return;
}
}
}
Member Class:
public class Member
{
private int month;
private int year;
private String name;
/*private Society society;*/
private List<Society> societies;
private boolean feesPaid;
public Member(String name, int month, int year /*Society society*/)
{
this.name = name;
this.month = month;
this.year = year;
this.societies = new ArrayList<>();
}
public void joinSociety(Society society)
{
societies.add(society);
}
public boolean isFeesPaid() {
return feesPaid;
}
public int getYear()
{
return year;
}
public int getMonth()
{
return month;
}
public String getName()
{
return name;
}
public String toString()
{
return "Name: " + name + ", Month Joined: " + month + ", Year Joined: " + year;
}
You can create a new List in removeMembers() method and add the removed objects to list and return it. remove(Object o) method in arraylist will return the removed object and remaining methods remove(int index), removeIf(Predicate<? super E> filter) and removeRange(int fromIndex, int toIndex) will not return removed object
public List<Members> removeMembers(int month, int year) {
List<Members> deletedMembers= new ArrayList<>();
Iterator<Members> members = myMembers.iterator();
while (members.hasNext()) {
Member member = members.next();
if (member.getYear()==year && member.getMonth()==month) {
deletedMembers.add(members.remove());
}
}
return deletedMembers;
}
I've implemented the interface comparable and the method compareTo(). I have a list named randomHumans that contains 10 objects. 5 objects with three fields: name, age and year they started studying, and 5 objects with two fields: name and age. I would like to sort my list, and tried using:
Collections.sort(randomHumans);
This gave me the following error message:
The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Object>)
I then tried this code:
Collections.sort((List<T>) randomObjects);
But it just gives me two new error messages. Maybe I need to specify what field it should sort after, but I can't find how to implement this. Any help would be greatly appreciated.
main method:
public static void main (String[] args) {
ArrayList<Object> randomObjects = new ArrayList<Object>();
for (int j=0; j<5; j++) {
Fysiker randomFysiker = new Fysiker();
randomObjects.add(randomFysiker);
Human randomHuman = new Human();
randomObjects.add(randomHuman);
}
System.out.println(randomObjects.toString());
//Collections.sort(randomObjects);
}
Human class:
class Human implements Comparable<Human> {
int age;
String name;
public Human (int myAge, String myName) {
name = myName;
age = myAge;
}
public Human() {
this(randomAge(),randomName());
}
public int compareTo(Human o) {
return this.age - o.age;
}
protected static int randomAge() {
Random randomGenerator = new Random();
return randomGenerator.nextInt(100);
}
protected static String randomName() {
Random randomGenerator = new Random();
return "Name"+randomGenerator.nextInt(15);
}
public int getAge(){
return age;
}
public String getName() {
return name;
}
public String toString() {
return "\nName: " + name + "\nAge: " + age + " yrs old\n";
}
}
Fysiker class:
public class Fysiker extends Human {
int year;
public Fysiker(int myAge2, String myName2, int myYear) {
name = myName2;
year = myYear+1932;
if (myAge2 >= 15+(2017-myYear)) {
age = myAge2;
} else {
age = 15+(2017-year);
}
}
public Fysiker() {
this(randomAge(),randomName(), randomYear());
}
protected static int randomYear() {
Random randomGenerator = new Random();
return randomGenerator.nextInt(83);
}
public int getYear(){
return year;
}
public String toString() {
return "\nName: " + name + "\nAge: " + age + " yrs old" + "\nStarted Physics: " + year+"\n";
}
}
Just change the generic parameter from Object to Human
public static void main (String[] args) {
List<Human> randomObjects = new ArrayList<>();
for (int j = 0; j < 5; j++) {
Fysiker randomFysiker = new Fysiker();
randomObjects.add(randomFysiker);
Human randomHuman = new Human();
randomObjects.add(randomHuman);
}
System.out.println(randomObjects);
Collections.sort(randomObjects);
}
When you write Collections.sort(randomHumans); randomHumans must be a List of Comparable. If you are 'forced' to use a List of Object, you must give a Comparator to explain how to compare each object :
Collections.sort(randomHumans, humanComparator);
It's all explained in the offcial documentation :
sort(java.util.List)
sort(java.util.List, java.util.Comparator)