?
Solved

SortedSet

Posted on 2003-02-22
13
Medium Priority
?
189 Views
Last Modified: 2010-05-18
Hi.
I've got a Vector, containing Appointment objects.
Each Appointment object contains date, start time, end time and description.

eg.
Date       Start Time   End    
21/02/2003   09:00      10:00
21/02/2003   07:00      08:00

I need to sort the appointment according to date, n in the example above, if the dates are the same, i need to sort according to the start time in ascending order.
How can i implement this using SortedSet?

Thank you.
0
Comment
Question by:danadanny
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +4
13 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 7998685
Can you post the class Appointment?
0
 
LVL 1

Accepted Solution

by:
shji1 earned 200 total points
ID: 7998737
I would try using the java.util.Date class in order to hold the date and the start time.
You can create a Date object by using:
Date d = DateFormat.getDateInstance().parse("21/02/2002 9:0"); // never tested it...
Or - A better way, in my opinion:
Date d = (new GregorianCalendar(2002,02,21,9,0)).getTime();

Since Date object are Comparables you can easily compare 2 dates, so you can pretty much easily create a Comparator to be used in your SortedSet (or TreeSet).
--Shaji
0
 
LVL 1

Expert Comment

by:shji1
ID: 7998787
I would try using the java.util.Date class in order to hold the date and the start time.
You can create a Date object by using:
Date d = DateFormat.getDateInstance().parse("21/02/2002 9:0"); // never tested it...
Or - A better way, in my opinion:
Date d = (new GregorianCalendar(2002,02,21,9,0)).getTime();

Since Date object are Comparables you can easily compare 2 dates, so you can pretty much easily create a Comparator to be used in your SortedSet (or TreeSet).
--Shaji
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 1

Expert Comment

by:shji1
ID: 7998808
I would try using the java.util.Date class in order to hold the date and the start time.
You can create a Date object by using:
Date d = DateFormat.getDateInstance().parse("21/02/2002 9:0"); // never tested it...
Or - A better way, in my opinion:
Date d = (new GregorianCalendar(2002,02,21,9,0)).getTime();

Since Date object are Comparables you can easily compare 2 dates, so you can pretty much easily create a Comparator to be used in your SortedSet (or TreeSet).
--Shaji
0
 
LVL 3

Expert Comment

by:allahabad
ID: 7999648
1. Implement Comparable iterface for Appointment object.

ex.

import java.util.*;
public class Appointment implements Comparable {

   String date;
   String startTime;
   String end;


   public Appointment(String date, String time, String end){

      this.date = date;
      this.startTime = time;
      this.end = end;


   }

   public String toString(){


      return (date + " : " + startTime + " : " + end);
   }

   public int compareTo(Object o){

     
      String objectDate = ((Appointment)o).getDate();
      String objectStartTime = ((Appointment)o).getStartTime();
      String objectEnd = ((Appointment)o).getEnd();


      if (objectDate.compareTo(date) >0) return -1;
      if (objectDate.compareTo(date) <0)return 1;

      if (objectDate.compareTo(date) == 0) {
         if (objectStartTime.compareTo(startTime) >0) return -1;
         if (objectStartTime.compareTo(startTime) <0) return 1;

         if (objectStartTime.compareTo(startTime) ==0) {
            if ( objectEnd.compareTo(end) > 0) return  -1;
            if ( objectEnd.compareTo(end) < 0 ) return 1;

         }

      }

      return 0;



   }

   public String getDate(){
      return date;
   }

   public String getStartTime(){
      return startTime;
   }

   public String getEnd(){
      return end;
   }


}

2. Use TreeSet (SortedSet type) to sort the contents of the
Vector object that holds Appointment objects.

ex.
import java.util.*;

public class SortApointment {


   public static void main(String args[]){


      Vector appList = new Vector();

      appList.add(new Appointment("22/02/2003","06:00","05:00"));
      appList.add(new Appointment("21/10/2003","09:00","10:00"));
      appList.add(new Appointment("21/02/2003","07:00","08:00"));
     

      TreeSet ts = new TreeSet(appList);

      Iterator it = ts.iterator();

      while(it.hasNext()){

         Appointment ap = (Appointment) it.next();
         System.out.println(ap.toString());

      }

   
   }


}
0
 
LVL 2

Expert Comment

by:functionpointer
ID: 8000110
you really should just use 2 java.util.Date objects, not Strings. Which date are you going to use when the appointment starts one minute before midnight and lasts 10 hours? And if it doesnt cross midnight to you, you can be sure it crosses midnight to someone, somewhere.
If you do switch to Dates, you will be able to simply check the .before(), .after() to sort, include simple methods to return the duration of appointment, and use java.util.DateFormat to print accurate times for the user, whereever they may be.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8000173
You can't implement reliable sorting in this way, as you are sorting the dates as strings, which is not a rational way of going about this. allahabad's code will fail as a result. You *could* decompose the date into its tokens and compare each token, but you'd be wiser following the suggestion of shji1, particularly as the start time is logically connected to the date anyway. The 'end time' should also be held as a Date too. This doesn't, btw, prevent you from also storing the component parts as Strings simultaneously.

This is why i asked you to post the definition of Appointment, as i suspected you are storing the component parts as Strings, and it seems that allahabad also suspects this ;-)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8000178
Well, functionpointer posted that as i was typing - convinced yet?
0
 
LVL 3

Expert Comment

by:NetWize
ID: 8002421
This won't work with the Date mentioned above!

Date       Start Time   End    
21/02/2003   09:00      10:00
21/02/2003   09:00      11:00

Keep in mind that your SortedSet can have no duplicate keys (by definition) so you won't be able to store two appointments with same date and starttime if you use the Date with these two values!

I suggest your class should implement the Comparable. It's OK to use the date for compare as long as date and starttime are different if the are equal you may need to take the end-time as additional sorting criteria.

Jan
0
 
LVL 2

Expert Comment

by:functionpointer
ID: 8003673
NetWize brings forth an interesting point...  BUT- unless you are a doctor, lawyer, dentist, or politician, why would you want to schedule multiple appointments at the same time?
Seriously though, some broken down and tired old Java guru once told me, "If you haven't overridden equals() and hashcode(), you haven't finished creating your class...". There is some powerful truth in that. You have to ask yourself if you want to compare actual object instances, or start-end dates, appointment attendees, etc. Dont be afraid to create methods like equalStartTime(Appointment a), or equalEndTime(Appointment a), or equalAttendees(Appointment a).
So you enhance your Appointment class to include a member String[] appointmentAttendees, or a member String appointmentChair and use these to make the appointment unique when you override hashcode(). If you are creating a real scheduling system, these items are an integral part of the uniqueness of the Appointment. How else would you schedule appointments for multiple persons or attendees?
In the case where the application sets appointments for a single user, wouldn't it be nice to know the subject or topic of the meeting?
A shortcut will only lead to unmaintainable and unreusable code. I don't think I have ever heard a client say, "Oh gosh, do this over. This program is too functional." On the other hand, I have heard many a programmer, including myself, say, "Damn... I've done this before... How did I do that one thing? Hmmmm." tick,tock,tick,tock... $ has left the building
 
0
 

Expert Comment

by:CleanupPing
ID: 9059146
danadanny:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0
 
LVL 7

Expert Comment

by:tomboshell
ID: 9582311
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:
Accept shji1's comment as answer.

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Thomas Boshell
EE Cleanup Volunteer
0

Featured Post

Enroll in August's Course of the Month

August's CompTIA IT Fundamentals course includes 19 hours of basic computer principle modules and prepares you for the certification exam. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Suggested Courses
Course of the Month11 days, 7 hours left to enroll

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question