Results 1 to 10 of 10

Thread: Hashmap issue.

  1. #1
    kay19 is offline Member
    Join Date
    May 2013
    Posts
    11
    Rep Power
    0

    Default Hashmap issue.

    Hey, i'm nearly finished with this code, but I can't figure this problem out. I have to ascend by last name, then first, then ID number. So if two employees have the same last name, then they would be sorted by first name. If they have the same firstname as well, then they have to be sorted by ID. My code is if they both have the same first and last name, then whoever has the highest ID number gets omitted from the list rather than being added. Either it's my Equals method I have to redo, or my case method, or both. Here are two of my codes, any guidance/advice on how to fix it is appreciated.

    Java Code:
    public class Employee implements Comparable {
    private String firstName; 
    private String lastName;
    private int id;
    private int perfScale;
    
    Employee() {
    	firstName = "";
    	lastName = "";
    	id = 0;
    	perfScale = 0;
    	}
    
    Employee(String lastName, String firstName, int id, int perfScale){
    	this.firstName = firstName;
    	this.lastName = lastName;
    	this.id = id;
    	this.perfScale = perfScale;
    }
    public String getLastName() {
    	return lastName;
    }
    public void setLastName(String lastName){
    	this.lastName = lastName;
    }
    public String getFirstName() {
    	return firstName;
    }
    public void setFirstName(String firstName){
    	this.firstName = firstName;
    }
    public int getId() {
    	return id;
    }
    public void setId(int id){
    	this.id = id;
    }
    public int getPerfScale() {
    	return perfScale;
    }
    public void setPerfScale(int perfScale){
    	this.perfScale = perfScale;
    }
    
    /* 2nd Attempt
    public boolean equals(Object o) {
    	if(o instanceof Employee)
    		return(getLastName() == ((Employee) o) .getLastName()) &&
    			(getFirstName() == ((Employee)o) .getFirstName()) &&
    			(getId() == ((Employee)o) .getId());
    	else
    		return false;
    }
    
    public int compareTo(Object o) {
    Employee e = (Employee) o;
    if (this.lastName.equals(((Employee) o).lastName)){
    	if(this.firstName.equals(((Employee) o) .firstName)){
    		return (this.id - e.getId());}
    	else
    		return(this.firstName.compareTo(((Employee) o).firstName));
    	}
     else
    	return(this.lastName.compareTo(((Employee) o).lastName));
    }
    
    
    public int hashCode() {
    	int h1 = firstName.hashCode();
    	int h2 = lastName.hashCode();
    	int h3 = new Integer(id).hashCode();
    	final int HASH_MULTIPLIER1 = 29;
    	final int HASH_MULTIPLIER2 = 19;
    	final int HASH_MULTIPLIER3 = 17;
    	int h = HASH_MULTIPLIER1 * h1 + HASH_MULTIPLIER2 * h2 + HASH_MULTIPLIER3 * h3;
    	return h;
    }
    	
    public String toString()
    {
    	return getLastName() + ", " + getFirstName() + " ID: " + getId() + " Performance Scale: " + getPerfScale();
    
    }
    }
    Here's my main method. The 5th case(Ascendinglastname) may be the issue as well. All the other cases seem to work well.

    Java Code:
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Scanner;
    import java.util.Set;
    import java.util.TreeMap;
    import java.util.TreeSet;
    
    public class EmployeeTest {
    	public static void main(String[] args) {
    		TreeMap<String, Employee> firstAndLast = new TreeMap<String, Employee>(); 
    		TreeMap<Integer, Employee> idNumber = new TreeMap<Integer, Employee>();
    		TreeMap<Employee, Integer> performanceScale = new TreeMap<Employee, Integer>();
    		TreeSet<Integer> sort = new TreeSet<Integer>();
    
    		Scanner keyboardInput = new Scanner(System.in);
    		
    		boolean exit = false;
    		
    		int choice;
    		while (exit != true) {
    			System.out.println("//-----MENU-----//");
    			System.out.println("1. Add an Employee ");
    			System.out.println("2. Remove an Employee ");
    			System.out.println("3. Modify performance scale ");
    			System.out.println("4. Print all the performance scale ");
    			System.out.println("5. Sort first and last name based on ID ");
    			System.out.println("6. Exit the program.");
    			System.out.print("Enter choice: ");
    
    			choice = keyboardInput.nextInt();
    
    			switch (choice) {
    			case 1:
    				addEmployee(firstAndLast, idNumber, performanceScale);
    				break;
    			case 2:
    				removeEmployee(firstAndLast, idNumber, performanceScale);
    				break;
    			case 3:
    				modifyPerformanceScale(idNumber, performanceScale);
    				break;
    			case 4:
    				printAllperfScale(performanceScale);
    				break;
    			case 5:
    				printLastNameAscending(firstAndLast, idNumber);
    				break;
    			case 6:
    				exit = true;
    				System.out.println("Exiting program...");
    				break;
    			default:
    				System.out
    						.println("Please choose a number from 1 - 5 from the menu.");
    			}
    		}// end while
    		
    	} // end main
    
    	public static void addEmployee(TreeMap<String, Employee> firstAndLastMap,
    			TreeMap<Integer, Employee> idNumberMap,
    			TreeMap<Employee, Integer> performanceScale) {
    		Scanner keyboardInput = new Scanner(System.in);
    		String firstName;
    		String lastName;
    		int id;
    		int perfScale;
    
    		System.out.print("Enter first name for the Employee: ");
    		firstName = keyboardInput.nextLine();
    		System.out.print("Enter last name for the Employeer: ");
    		lastName = keyboardInput.nextLine();
    		System.out.print("Enter ID number of the Employee: ");
    		id = keyboardInput.nextInt();
    		System.out.print("Enter Performance Scale rating between 1 to 5: ");
    		perfScale = keyboardInput.nextInt();
    
    		Employee addEmployee = new Employee(lastName, firstName, id, perfScale);
    		
    		firstAndLastMap.put(lastName + ", " + firstName, addEmployee);
    		idNumberMap.put(id, addEmployee);
    		//changed - Added(addEmployee,perfScale) from put(perfScale)
    		performanceScale.put(addEmployee, perfScale);
    		
    	}
    
    	public static void removeEmployee(TreeMap<String, Employee> firstAndLastMap,
    			TreeMap<Integer, Employee> idNumberMap,
    			TreeMap<Employee, Integer> performanceScale) {
    
    		Scanner keyboardInput = new Scanner(System.in);
    		String firstName;
    		String lastName;
    		int id;
    		System.out.print("Enter First name of Employee you want to remove: ");
    		firstName = keyboardInput.nextLine();
    		System.out.print("Enter last name of Employee you want to remove: ");
    		lastName = keyboardInput.nextLine();
    		
    		System.out.print("Enter ID number of Employee you want to remove: ");
    		id = keyboardInput.nextInt();
    		//System.out.println();
    		
    	
    		firstAndLastMap.remove(lastName + ", " + firstName);
    		idNumberMap.remove(id); 
    		//should be remove(perfScale)
    
    	}
    //changed TreeMap<String, emp...to <Integer, emp
    	public static void modifyPerformanceScale(TreeMap<Integer, Employee> idNumber, TreeMap<Employee, Integer> performanceScale) {
    	    System.out.print("Enter ID: ");
    	    Scanner keyboardInput = new Scanner(System.in);
    
    	    int idNumber1;
    	    int modScale;
    	    idNumber1 = keyboardInput.nextInt();
    
    	    System.out.print("Enter the number you want to change to: ");
    	    modScale = keyboardInput.nextInt();
    
    	    Employee employee = idNumber.get(idNumber1);
    	    performanceScale.put(employee, modScale);
    	}
    
    	public static void printAllperfScale(TreeMap<Employee,Integer> performanceScale) {
    		Set Employee1 = performanceScale.entrySet();	
    		Iterator itr1 = Employee1.iterator();
    
    		while (itr1.hasNext()) {
    			Map.Entry me = (Map.Entry) itr1.next();
    			System.out.println(me.getValue());
    		}
    	}
    
    
    	public static void printLastNameAscending(TreeMap<String, Employee> LastName,
    			TreeMap<Integer, Employee>idNumber) {
    		Set Employee1 = LastName.entrySet();
    		Set Employee2 = idNumber.entrySet();
    		Iterator itr1 = Employee1.iterator();
    		Iterator itr2 = Employee2.iterator();
    
    		while (itr1.hasNext() && itr2.hasNext()) {
    			Map.Entry me = (Map.Entry) itr1.next();
    			Map.Entry be = (Map.Entry) itr2.next();
    			System.out.print(me.getValue()+ " ID: ");
    			System.out.println(be.getValue());
    		}
    		
    	}
    
    } // end

  2. #2
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

    Default Re: Hashmap issue.

    You're comparing Strings with == ! Never do that unless you do want to compare the instances. Fix that first and test again.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  3. #3
    kay19 is offline Member
    Join Date
    May 2013
    Posts
    11
    Rep Power
    0

    Default Re: Hashmap issue.

    Alright thanks PhHein. I was looking at compareTo & Boolean equals method, and notice that I use equals with compareTo, but "==" in the boolean equals. Will redo my method.

  4. #4
    kay19 is offline Member
    Join Date
    May 2013
    Posts
    11
    Rep Power
    0

    Default Re: Hashmap issue.

    heya, I modified my equals method and my main compiler method, but not getting my results. So this is what it does. When I input the 2nd Employee's similar first and last name, It replaces the other employee along with their ID number & Performance Rating.
    Specifically changed:

    Java Code:
    public boolean equals(Object o) {
    	if(o instanceof Employee)
    		return(this.getLastName().equalsIgnoreCase(((Employee) o).getLastName()) &&
    			(this.getFirstName().equalsIgnoreCase(((Employee)o) .getFirstName()) &&
    			(this.getId() == ((Employee)o) .getId())));
    	else
    		return false;
    }
    & main file change:
    Java Code:
    	public static void printLastNameAscending(TreeMap<String, Employee> firstAndLast,
    			TreeMap<Integer, Employee>idNumber) {
    		Set Employee2 = firstAndLast.entrySet();
    		Iterator itr2 = Employee2.iterator();
    		while (itr2.hasNext()) {
    			Map.Entry fe = (Map.Entry) itr2.next();
    			System.out.println(fe.getValue());
    		}
    		
    	}
    Still attempting to rework my main compile method if that is the problem.

  5. #5
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,414
    Rep Power
    5

    Default Re: Hashmap issue.

    Well, I am not certain this is the problem. Your hashCodes must be equal if the equals returns true. But your hashCode on the names is case sensitive while your equals method does a case insensitive comparison.

    Regards,
    Jim
    Last edited by jim829; 10-29-2013 at 08:16 PM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  6. #6
    kay19 is offline Member
    Join Date
    May 2013
    Posts
    11
    Rep Power
    0

    Default Re: Hashmap issue.

    Ok thanks for your reply, i'll reexamine my code and start fixing.

  7. #7
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,414
    Rep Power
    5

    Default Re: Hashmap issue.

    Actually, I am probably wrong. Your hashCode only applies to the Employee class which is not used as a key in the firstAndLast TreeMap.

    But do make certain you don't change your keys while they are active in any Map implementation. If you do the lookup will likely fail. If possible,
    it is best to use immutable objects as keys to maps.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  8. #8
    kay19 is offline Member
    Join Date
    May 2013
    Posts
    11
    Rep Power
    0

    Default Re: Hashmap issue.

    Alright, thanks once again. i'll look into my TreeMap and examine my code more thoroughly.

  9. #9
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,414
    Rep Power
    5

    Default Re: Hashmap issue.

    I think I figured out the problem. When the user changes the performance value you fail to set it in the employee class. Since you use the Employee toString() method to display those values, the change is never shown.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  10. #10
    kay19 is offline Member
    Join Date
    May 2013
    Posts
    11
    Rep Power
    0

    Default Re: Hashmap issue.

    Update. I finished, but my main file I had to scrap it, and had help from classmate. So for future reference:
    Java Code:
    	public static void main(String[] ar) {
    		String first, last;
    		int num, id, scale;
    	Map<Employee, Integer> Scale = new TreeMap<Employee, Integer>();
    	Map<Integer, Employee> Empl = new TreeMap<Integer, Employee>();
    	Scanner scw = new Scanner(System.in);
    	Scanner scn = new Scanner(System.in);
    	
    	do
    	  {
    	   System.out.println("1. Print all");
    	   System.out.println("2. Add");
    	   System.out.println("3. Remove");
    	   System.out.println("4. Modify Peformance Scale");
    	   System.out.println("5. Exit");
    	   System.out.print("Enter Number: ");
    	   num = scn.nextInt();
    	   
     if(num ==1)
     {
    	   
    	   if(Empl.isEmpty())
    	   
       	{
       		System.out.println("Empty List");
       	}
    	   else{
    	Set<Employee> keyset = Scale.keySet();
       	System.out.println("Print all Perfomance Scale");
    	for(Employee key: keyset)
    		{
    			int value = Scale.get(key);
    			System.out.println(key + " : " + value);
    		}
    		System.out.println();
    	   }
     }
    if (num==2)
    {
    	    	System.out.print("\nEnter ID : ");
    	    	id = scn.nextInt();
    	    	
    	    	if(Empl.containsKey(id))
    	    		System.out.print("\nID is used.\n");
    	    	else
    	    	{
    	    		System.out.print("Enter first name : ");
    	    		first = scw.nextLine(); 
    	    		System.out.print("Enter last name : ");
    	    		last = scw.nextLine();
    	    		System.out.print("Enter the peformance scale(1 to 5) : ");
    	    		scale = scn.nextInt();
    	    		Employee newE = new Employee(last, first, id);
    	    		Empl.put(id, newE);
    	    		Scale.put(newE, scale);
    	    		System.out.println("ADDED on the List");
    	    	}
    }
    if(num==3)
    {
    	    	if(Empl.isEmpty())
    	    	{
    	    		System.out.println("Empty List  ");
    	    		System.out.println("");
    	    	}
    	    	else{
    	    	System.out.print("\nEnter ID : ");
    	    	id = scn.nextInt();
    	    	
    	    	if(!Empl.containsKey(id))
    	    		System.out.println("Can't find");
    	    	else
    	    	{
    	    		Employee temp = Empl.get(id);
    	    		Empl.remove(id);
    	    		Scale.remove(temp);
    	    		System.out.println("Deleted");
    	    	}
    	    	}
    }
    if(num==4)
    {
    	    	if(Empl.isEmpty())
    	    	{
    	    		System.out.println("Empty List ");
    	    	
    	    	}
    	    	else{
    	    	System.out.println("\nEnter ID : ");
    	    	id = scn.nextInt();
    	    	if(!Empl.containsKey(id))
    	    		System.out.println("\nID doesn't exist.\n");
    	    	else
    	    	{
    	    		Employee temp2 = Empl.get(id);
    	    		System.out.println("Enter a new Perfomance Scale : ");
    	    		scale = scn.nextInt();
    	    		Scale.put(temp2, scale);
    	    		System.out.println("Changed");
    	    	}
    	    	}
    }
    if(num==5)
    {
    		   System.out.println("Program ended.");
    }
    if(num != 1 &&num != 2&&num != 3&&num != 4&&num != 5){
    	    	System.out.println("Wrong number");
    	 
    }  
    	  }while(num != 5);
    	}
    	
    }

Similar Threads

  1. Replies: 0
    Last Post: 02-27-2012, 02:39 AM
  2. Regular Expression issue and setName() method issue
    By geforce in forum New To Java
    Replies: 2
    Last Post: 01-30-2012, 03:33 AM
  3. HashMap
    By Shukaib_khan in forum New To Java
    Replies: 4
    Last Post: 12-25-2011, 12:51 PM
  4. final HashMap hm=new HashMap();
    By sangramkeshari.jena in forum New To Java
    Replies: 4
    Last Post: 07-21-2011, 09:44 PM
  5. Replies: 7
    Last Post: 12-08-2009, 07:17 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •