Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Student TreeMap

  1. #1
    Junior Member
    Join Date
    Feb 2010
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Student TreeMap

    Hi all, my assignment is to use TreeMap to sort Student objects. Students have a first name, a last name, and a unique integer ID. The sample program looks like so:

    Sample Program
    A)dd R)emove M)odify P)rint Q)uit
    [COLOR="blue"]A[/COLOR]
    Enter the student's first name:
    [COLOR="blue"]Joe[/COLOR]
    Enter the student's last name:
    [COLOR="Blue"]Smith[/COLOR]
    Enter the student's ID:
    [COLOR="blue"]1001[/COLOR]
    Enter the student's grade:
    [COLOR="blue"]C[/COLOR]
    A)dd R)emove M)odify P)rint Q)uit
    [COLOR="blue"]A[/COLOR]
    Enter the student's name:
    [COLOR="blue"]Sarah[/COLOR]
    Enter the student's last name:
    [COLOR="blue"]Smith[/COLOR]
    Enter the student's ID:
    [COLOR="blue"]1002[/COLOR]
    Enter the student's grade:
    [COLOR="blue"]B+[/COLOR]
    A)dd R)emove M)odify P)rint Q)uit
    [COLOR="blue"]A[/COLOR]
    Enter the student's first name:
    [COLOR="blue"]Joe[/COLOR]
    Enter the student's last name:
    [COLOR="blue"]Smith[/COLOR]
    Enter the student's ID:
    [COLOR="blue"]2003[/COLOR]
    Enter the student's grade:
    [COLOR="blue"]B+[/COLOR]
    A)dd R)emove M)odify P)rint Q)uit
    [COLOR="blue"]A[/COLOR]
    Enter the student's first name:
    [COLOR="blue"]Harry[/COLOR]
    Enter the student's last name:
    [COLOR="blue"]Pham[/COLOR]
    Enter the student's ID:
    [COLOR="blue"]1996[/COLOR]
    Enter the student's grade:
    [COLOR="blue"]F[/COLOR]
    A)dd R)emove M)odify P)rint Q)uit
    [COLOR="blue"]M[/COLOR]
    Enter the student's ID:
    [COLOR="blue"]1002[/COLOR]
    Enter the student's grade:
    [COLOR="blue"]A[/COLOR]
    A)dd R)emove M)odify P)rint Q)uit
    [COLOR="blue"]R[/COLOR]
    Enter the student's ID:
    [COLOR="blue"]1996[/COLOR]
    A)dd R)emove M)odify P)rint Q)uit
    [COLOR="blue"]P[/COLOR]
    Joe Smith 1001: C
    Joe Smith 2003: B+
    Sarah Smith 1002: A
    A)dd R)emove M)odify P)rint Q)uit
    [COLOR="blue"]Q[/COLOR]

    When I add a student, it is supposed to sort it by last name first, then by first name, and then by student ID number. I was able to do this just fine, however I ran into problems when trying to remove, modify, or print out my list. Here are my Student and GradeBook classes:

    Student
    public class Student
    {
    	public Student( String aFirstName, String aLastName, int aStudentId )
    	{
    		firstName = aFirstName;
    		lastName = aLastName;
    		studentId = aStudentId;
    	}
     
    	public String getFirstName()
    	{
    		return firstName;
    	}
     
    	public String getLastName()
    	{
    		return lastName;
    	}
     
    	public int getStudentId()
    	{
    		return studentId;
    	}
     
    	public String toString()
    	{
    		return firstName + " " + lastName + " " + studentId;
    	}
     
    	private String firstName;
    	private String lastName;
    	private int studentId;
    }

    GradeBook
    import java.util.Scanner;
    import java.util.TreeMap;
    import java.util.Map;
    import java.util.Set;
    import java.util.Comparator;
     
    public class GradeBook5
    {
    	public static void main(String[] args)
    	{
    		Scanner in = new Scanner(System.in);
     
    		class StudentComparator implements Comparator<Student>
    		{
    			public int compare( Student a, Student b )
    			{
    				if( a.getLastName().compareTo(b.getLastName() ) < 0 ) return -1;
    				if( a.getLastName().compareTo(b.getLastName() ) == 0 )
    				{
    					if( a.getFirstName().compareTo(b.getFirstName() ) < 0 ) return -1;
    					if( a.getFirstName().compareTo(b.getFirstName() ) == 0 )
    					{
    						if( a.getStudentId() < b.getStudentId() ) return -1;
    						return 1;
    					}
    					return 1;
    				}
    				return 1;
    			}
    		}
     
    		Comparator<Student> comp = new StudentComparator();
    		Map<Student, String> students = new TreeMap<Student, String>(comp);
    		Map<Integer, Student> id = new TreeMap<Integer, Student>();
     
    		System.out.println( "A)dd R)emove M)odify P)rint Q)uit" );
    		String answer = in.nextLine();
     
    		while( !answer.equalsIgnoreCase("Q") )
    		{
    			if( answer.equalsIgnoreCase("A") )
    			{
    				System.out.println( "Enter the student's first name:" );
    				String firstName = in.nextLine();
    				System.out.println( "Enter the student's last name:" );
    				String lastName = in.nextLine();
    				System.out.println( "Enter the student's ID:" );
    				int studentId = in.nextInt();
    				String trash = in.nextLine();
    				System.out.println( "Enter the student's grade:" );
    				String grade = in.nextLine();
     
    				Student s = new Student( firstName, lastName, studentId );
    				students.put( s, grade );
    				id.put( studentId, s );
    			}
    			else if( answer.equalsIgnoreCase("R") )
    			{
    				System.out.println( "Enter the student's ID:" );
    				int studentId = in.nextInt();
    				String trash = in.nextLine();
     
    				Student s = id.get( studentId );
    				System.out.println( students.remove( s ) );
    				id.remove( studentId );
    			}
    			else if( answer.equalsIgnoreCase("M") )
    			{
    				System.out.println( "Enter the student's ID:" );
    				int studentId = in.nextInt();
    				String trash = in.nextLine();
     
    				Student s = id.get( studentId );
     
    				System.out.println( "Enter the student's grade:" );
    				String grade = in.nextLine();
     
    				students.put( s, grade );
    				id.put( studentId, s );
    			}
    			else if( answer.equalsIgnoreCase("P") )
    			{
    				Set<Student> keySet = students.keySet();
    				System.out.println( students.keySet() );
     
    				for( Student key : keySet )
    				{
    					String value = students.get( key );
    					System.out.println( key.toString() + ": " + value );
    				}
    			}
     
    			System.out.println( "A)dd R)emove M)odify P)rint Q)uit" );
    			answer = in.nextLine();
    		}
    	}
    }

    When printing out the list, it does not seem to want to print out the grade (value of the students TreeMap). Also, I cannot seem to remove a Student from either TreeMap nor can I modify them. What am I doing wrong?


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,296
    Thanks
    180
    Thanked 824 Times in 767 Posts
    Blog Entries
    5

    Default Re: Student TreeMap

    When placing classes you wrote into classes which implement Map and Set interfaces, you need to make sure that the equals() and hashCode() methods are overridden. Because of the hash based retrieval of the implemented interfaces, without doing so you can risk not being able to retrieve the objects once they are placed in the Map or Set.
    See Java theory and practice: Hashing it out

  3. #3
    Junior Member
    Join Date
    Feb 2010
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Student TreeMap

    Thanks, so I should implement equals() and hashCode() into my GradeBook class?

    public boolean equals( Object otherObject )
    {
    	if( otherObject == null ) return false;
    	if( getClass() != otherObject.getClass() ) return false;
    	Student other = (Student) otherObject;
    	return getStudentId() == other.getStudentId();
    }

    Would this be the right way to code my equals method if I am trying to find students by their ID number?

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,296
    Thanks
    180
    Thanked 824 Times in 767 Posts
    Blog Entries
    5

    Default Re: Student TreeMap

    Because you are adding the Student object to your TreeMap, you should over-ride them in that class (similar to the equals you posted). It might be a bit trickier to override them though if you wish to retrieve Student from the map based upon an Integer (ID) AND a String (name), because you can only use one. So you should decide which to use, or determine a workaround to the problem if you wish to use both

  5. #5
    Junior Member
    Join Date
    Feb 2010
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Student TreeMap

    I only need to retrieve the Student object when the user requests to Remove or Modify one of the Students and that is done through their Integer ID. Adding the equals() method that I coded above did not seem to have any effect on my program. I am still unable to modify or remove a Student. Also, the Student object (key) doesn't seem to be linked to their grade (value). When I try to print the results, I simply get:

    Harry Pham 1996: null
    Joe Smith 1001: null
    Joe Smith 2003: null
    Sarah Smith 1002: null
    Last edited by raphytaffy; March 1st, 2010 at 08:11 PM.

  6. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,296
    Thanks
    180
    Thanked 824 Times in 767 Posts
    Blog Entries
    5

    Default Re: Student TreeMap

    Quote Originally Posted by raphytaffy View Post
    I only need to retrieve the Student object when the user requests to Remove or Modify one of the Students and that is done through their Integer ID. Adding the equals() method that I coded above did not seem to have any effect on my program. I am still unable to modify or remove a Student. Also, the Student object (key) doesn't seem to be linked to their grade (value). When I try to print the results, I simply get:

    Harry Pham 1996: null
    Joe Smith 1001: null
    Joe Smith 2003: null
    Sarah Smith 1002: null
    Did you also override hashCode()?

    @Override public int hashCode(){
        return studentId;
    }

  7. #7
    Junior Member
    Join Date
    Feb 2010
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Student TreeMap

    Both are in my Student class:

    public class Student
    {
    	public Student( String aFirstName, String aLastName, int aStudentId )
    	{
    		firstName = aFirstName;
    		lastName = aLastName;
    		studentId = aStudentId;
    	}
     
    	public String getFirstName()
    	{
    		return firstName;
    	}
     
    	public String getLastName()
    	{
    		return lastName;
    	}
     
    	public int getStudentId()
    	{
    		return studentId;
    	}
     
    	public String toString()
    	{
    		return firstName + " " + lastName + " " + studentId;
    	}
     
    	public boolean equals( Object otherObject )
    	{
    		if( otherObject == null ) return false;
    		if( getClass() != otherObject.getClass() ) return false;
    		Student other = (Student) otherObject;
    		return getStudentId() == other.getStudentId();
    	}
     
    	public int hashCode()
    	{
    		return studentId;
    	}
     
    	private String firstName;
    	private String lastName;
    	private int studentId;
    }

    Am I doing something wrong?

Similar Threads

  1. [SOLVED] Help me with different activities in Java program
    By xyldon27 in forum Java Theory & Questions
    Replies: 10
    Last Post: June 9th, 2009, 09:42 AM