Hashmap duplicate entry and sorting

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;



public class TestHashMap9 {
	public static void main(String[] args) {
	//HashMap hashMap = new HashMap();
		
		HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
		Dog d1 = new Dog("red");
		Dog d2 = new Dog("black");
		Dog d3 = new Dog("white");
		Dog d4 = new Dog("white");
		
		hashMap.put(d1, 10);
		hashMap.put(d2, 15);
		hashMap.put(d3, 5);
		hashMap.put(d4, 20);

		//print size
		System.out.println(hashMap.size());
		
		//loop HashMap
		/*for (Entry entry : hashMap) {
		System.out.println(entry.getKey().toString() + " - " + entry.getValue());*/
			
			for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());
		}
	}
}

Open in new window


my code is as above.
i got output as below

4
white dog22 - 5
black dog22 - 15
white dog22 - 20
red dog22 - 10


why i am getting duplicate entry on white dog which happened to be key here.

Also how do i sort on above key

also how to sort on value so that 5,10,15,20 prints in order.
please advise
LVL 7
gudii9Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dpearsonCommented:
You should post the "Dog" class.

It needs to implement "hashCode" and "equals" to work correctly as a key inside a HashMap.
I'm guessing it is missing those methods?

There are examples on how to write those methods here:
http://tutorials.jenkov.com/java-collections/hashcode-equals.html

Or today most IDEs can just add them to your class automatically from a menu.

(For the sorting - switch to a TreeMap).

Doug
ozoCommented:
If your goal is to sort on integers, a way to do that can be to use integers as the key in a TreeMap
gudii9Author Commented:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;



public class TestTreeMap5{
public static void main(String[] args) {
	//HashMap hashMap = new HashMap();
		
	
	  ArrayList<Dog> list = new ArrayList<Dog>();

      list.add(new Dog("Shaggy",3));
      list.add(new Dog("Lacy",2));
      list.add(new Dog("Roger",10));
      list.add(new Dog("Tommy",4));
      list.add(new Dog("Tammy",1));
	
		Map<Integer, Dog> hashMap = new TreeMap<Integer, Dog>();
		Dog d1 = new Dog("red");
		Dog d2 = new Dog("black");
		Dog d3 = new Dog("white");
		Dog d4 = new Dog("green");
		
		hashMap.put(20, d3);
		hashMap.put(10, d1);
		hashMap.put(15, d2);	
		hashMap.put(20, d4); 

		//print size
		System.out.println(hashMap.size());
		
		
		for (Entry<Integer, Dog> intval1 : hashMap.entrySet()) {
			System.out.println(intval1.toString() );
			}
		
		//loop HashMap
		for (Dog intval : hashMap.values()) {
		System.out.println(intval.color);
		}
		for (Integer keyObj : hashMap.keySet()) {
			System.out.println(keyObj.toString() );
			
			
			
			/*for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());*/
		}
	}
}

Open in new window


like above right?
i got output as
3
10=red dog22
15=black dog22
20=green dog22
red
black
green
10
15
20


I do not understand why we need arrayList and again TreeMap both collection objects in this example. please advise
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

ozoCommented:
"need" is usually defined in reference to some goal.
What is your goal?
"need" can also be relative to what options you have for attaining a goal.
What are the options we are dealing with here?

Also, we still don't know what a Dog is because you haven't shown us how that class is defined.
dpearsonCommented:
I think you really need to tell us what you're looking to do.

Saying "it's not sorted" isn't enough - what are you trying to sort and in what order.

Can you show us an example of what you're expecting to get as output?

Doug
zzynxSr. Software engineerCommented:
You were asked to post the code of your Dog class.
You still haven't done that.

I also agree with this statement:
I think you really need to tell us what you're looking to do.

Don't make us guess what you're trying to do. Just tell us in a clear way. E.g. by giving one or more examples.
gudii9Author Commented:
class Dog {

String color;

 

Dog(String c) {

color = c;

}

public Dog(String string, int i) {
	// TODO Auto-generated constructor stub
}

public String toString(){  

return color + " dog22";

}

}

Open in new window


above ius my Dog class.

My need is to sort on Dog so that instead of below output

red
black
green

i should get below output



black
green
red

So how to know different options to fulfil a need towards a goal?
I do not understand why we need arrayList and again TreeMap both collection objects in this example. please advise
ozoCommented:
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.Collections;
class Dog  implements Comparable<Dog> {

    String color;
 

    Dog(String c) {

      color = c;

    }

    public Dog(String string, int i) {
      // TODO Auto-generated constructor stub
    }

    public String toString(){  

      return color + " dog22";

    }
    public int compareTo(Dog compareDog) {
          return this.color.compareTo(compareDog.color);
    }
};


public class TestTreeMap5{
    public static void main(String[] args) {

            TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();
            Dog d1 = new Dog("red");
            Dog d2 = new Dog("black");
            Dog d3 = new Dog("green");
            
            treeMap.put(d1, 10);
            treeMap.put(d2, 15);
            treeMap.put(d3, 5);

            for (Dog keyObj : treeMap.keySet()) {
                  System.out.println(keyObj.color );
            }
            
            ArrayList<Dog> list=new ArrayList<Dog>();
            list.add(d1);
            list.add(d2);
            list.add(d3);
            Collections.sort(list);
            for (Dog keyObj : list ){
                System.out.println(keyObj.color );
            }
      }
}
dpearsonCommented:
You don't need both a List and a TreeMap- I think showing both is confusing the issue.

You do however need to implement equals and hashcode for this to work correctly.  Objects you put into HashMap always need to implement those methods.  As I mentioned, your IDE should be able to do this for you - the code I'm showing here was auto generated for me.

Something like this:

import java.util.TreeMap;
class Dog implements Comparable<Dog> {

	String color;


	Dog(String c) {
		color = c ;
	}

	public Dog(String string, int i) {
		// TODO Auto-generated constructor stub
	}

	public String toString(){
		return color + " dog22";
	}

	public int compareTo(Dog compareDog) {
		return this.color.compareTo(compareDog.color);
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;

		Dog dog = (Dog) o;

		if (color != null ? !color.equals(dog.color) : dog.color != null) return false;

		return true;
	}

	@Override
	public int hashCode() {
		return color != null ? color.hashCode() : 0;
	}
};


public class TestMap{
	public static void main(String[] args) {

		TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();
		Dog d1 = new Dog("red");
		Dog d2 = new Dog("black");
		Dog d3 = new Dog("green");

		treeMap.put(d1, 10);
		treeMap.put(d2, 15);
		treeMap.put(d3, 5);

		for (Dog keyObj : treeMap.keySet()) {
			System.out.println(keyObj.color );
		}
	}
}

Open in new window

gudii9Author Commented:
@Override
public int hashCode() {
	final int prime = 31;
	int result = 1;
	result = prime * result + ((color == null) ? 0 : color.hashCode());
	return result;
}

@Override
public boolean equals(Object obj) {
	if (this == obj)
		return true;
	if (obj == null)
		return false;
	if (getClass() != obj.getClass())
		return false;
	Dog other = (Dog) obj;
	if (color == null) {
		if (other.color != null)
			return false;
	} else if (!color.equals(other.color))
		return false;
	return true;
}

Open in new window


i see option in eclipse to implement hashCode() and equals methods.

class Dog {

String color;

Dog(String c) {

	color = c;

}

@Override
public int hashCode() {
	final int prime = 31;
	int result = 1;
	result = prime * result + ((color == null) ? 0 : color.hashCode());
	return result;
}

@Override
public boolean equals(Object obj) {
	if (this == obj)
		return true;
	if (obj == null)
		return false;
	if (getClass() != obj.getClass())
		return false;
	Dog other = (Dog) obj;
	if (color == null) {
		if (other.color != null)
			return false;
	} else if (!color.equals(other.color))
		return false;
	return true;
}

public Dog(String string, int i) {
	// TODO Auto-generated constructor stub
}

public String toString() {

	return color + " dog22";

}

}

Open in new window


i wonder why we need to implement them to use in hashMap
gudii9Author Commented:
import java.util.ArrayList;
import java.util.Collections;
import java.util.TreeMap;

public class TestTreeMap6{
    public static void main(String[] args) {

            TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();
            Dog d1 = new Dog("red");
            Dog d2 = new Dog("black");
            Dog d3 = new Dog("green");
            
            treeMap.put(d1, 10);
            treeMap.put(d2, 15);
            treeMap.put(d3, 5);

            for (Dog keyObj : treeMap.keySet()) {
                  System.out.println(keyObj.color );
            }
            
            ArrayList<Dog> list=new ArrayList<Dog>();
            list.add(d1);
            list.add(d2);
            list.add(d3);
            Collections.sort(list);
            for (Dog keyObj : list ){
                System.out.println(keyObj.color );
                
            }
            
    }
    
}

Open in new window

Above code generating below error

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (ArrayList<Dog>). The
 inferred type Dog is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>


please advise
dpearsonCommented:
i wonder why we need to implement them to use in hashMap

A HashMap is like a libary.  The objects you store in it are like books and the code inside HashMap puts those books onto different shelves in the library.

For a HashMap to work it needs to know where to put the books and how to find them again.   In a real library we use the author's name or a special code on the back of the book to know where to find it - if I'm looking for a book by "Smith" it'll be on the "S" shelf.

 In a HashMap it does that using "hashCode" - it's like the author's name or the code on the back of a book in a library.  It tells the HashMap which shelf to put the book on and when it goes looking for it again, where to find it.

It also uses "equals" to decide when you go to add a new book to the library - do we already have a copy of this book or not?

Does that make sense?  Glad to see you found the Eclipse command to add these.

Doug

P.S. As for the array list error - my advice is skip the list code, you don't need it here.
gudii9Author Commented:
import java.util.ArrayList;
import java.util.Collections;
import java.util.TreeMap;

public class TestTreeMap6{
    public static void main(String[] args) {

            TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();
            Dog d1 = new Dog("red");
            Dog d2 = new Dog("black");
            Dog d3 = new Dog("green");
            
            treeMap.put(d1, 10);
            treeMap.put(d2, 15);
            treeMap.put(d3, 5);

            for (Dog keyObj : treeMap.keySet()) {
                  System.out.println(keyObj.color );
            }
            
            ArrayList<Dog> list=new ArrayList<Dog>();
            list.add(d1);
            list.add(d2);
            list.add(d3);
           // Collections.sort(list);
            for (Dog keyObj : list ){
                System.out.println(keyObj.color );
                
            }
            
    }
    
}

Open in new window


i see below error when i comment
Exception in thread "main" java.lang.ClassCastException: Dog incompatible with java.lang.Comparable
      at java.util.TreeMap.toComparable(TreeMap.java:5505)
      at java.util.TreeMap.putImpl(TreeMap.java:4546)
      at java.util.TreeMap.put(TreeMap.java:4536)
      at TestTreeMap6.main(TestTreeMap6.java:14)
dpearsonCommented:
You need the other changes to the Dog class:

class Dog implements Comparable<Dog> {
...
     public int compareTo(Dog compareDog) {
            return this.color.compareTo(compareDog.color);
      }

...
}
   

Check the code again that I and ozo posted earlier.
gudii9Author Commented:
It also uses "equals" to decide when you go to add a new book to the library - do we already have a copy of this book or not?

i wonder why we need to check this. I like this library analogy. very practical and easy to relate.
gudii9Author Commented:
   public int compareTo(Dog compareDog) {
            return this.color.compareTo(compareDog.color);
      }

Open in new window


why we need above method apart from hashCode() equals()?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;



public class TestTreeMap5{
public static void main(String[] args) {
	//HashMap hashMap = new HashMap();
		
	
	  ArrayList<Dog> list = new ArrayList<Dog>();

      list.add(new Dog("Shaggy",3));
      list.add(new Dog("Lacy",2));
      list.add(new Dog("Roger",10));
      list.add(new Dog("Tommy",4));
      list.add(new Dog("Tammy",1));
	
		Map<Integer, Dog> hashMap = new TreeMap<Integer, Dog>();
		Dog d1 = new Dog("red");
		Dog d2 = new Dog("black");
		Dog d3 = new Dog("white");
		Dog d4 = new Dog("green");
		
		hashMap.put(20, d3);
		hashMap.put(10, d1);
		hashMap.put(15, d2);	
		hashMap.put(20, d4); 

		//print size
		System.out.println(hashMap.size());
		
		
		for (Entry<Integer, Dog> intval1 : hashMap.entrySet()) {
			System.out.println(intval1.toString() );
			}
		
		//loop HashMap
		for (Dog intval : hashMap.values()) {
		System.out.println(intval.color);
		}
		for (Integer keyObj : hashMap.keySet()) {
			System.out.println(keyObj.toString() );
			
			
			
			/*for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());*/
		}
	}
}

Open in new window


class Dog {

String color;

Dog(String c) {

	color = c;

}

@Override
public int hashCode() {
	final int prime = 31;
	int result = 1;
	result = prime * result + ((color == null) ? 0 : color.hashCode());
	return result;
}

@Override
public boolean equals(Object obj) {
	if (this == obj)
		return true;
	if (obj == null)
		return false;
	if (getClass() != obj.getClass())
		return false;
	Dog other = (Dog) obj;
	if (color == null) {
		if (other.color != null)
			return false;
	} else if (!color.equals(other.color))
		return false;
	return true;
}

public int compareTo(Dog compareDog) {
    return this.color.compareTo(compareDog.color);
}

public Dog(String string, int i) {
	// TODO Auto-generated constructor stub
}

public String toString() {

	return color + " dog22";

}

}

Open in new window


above produced below
3
10=red dog22
15=black dog22
20=green dog22
red
black
green
10
15
20
gudii9Author Commented:
above produced below
3
10=red dog22
15=black dog22
20=green dog22
red
black
green
10
15
20


i expected it to be sorted on dog color as below


first black then green then red but i did not get that output. please advise
gudii9Author Commented:
You don't need both a List and a TreeMap- I think showing both is confusing the issue.

how do i acheive my goal of sorting the key(here dog object) without using List but just using HashMap/TreeMap.

Please advise
dpearsonCommented:
i expected it to be sorted on dog color as below

When I run the code I posted, this is what I get - which looks sorted to me:

black
green
red

Have you tried using my code?

how do i acheive my goal of sorting the key(here dog object) without using List but just using HashMap/TreeMap.
A TreeMap automatically sorts the keys put into it - that's what makes it different from an ordinary HashMap (which does not).

Again - see my code - it only uses a TreeMap and the output is sorted.

Doug
ozoCommented:
how do i acheive my goal of sorting the key(here dog object) without using List
Comment out the list code.

If your only goal is
i should get below output



black
green
red
then comment out the TreeMap code
gudii9Author Commented:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;



public class TestTreeMap5{
public static void main(String[] args) {
	HashMap hashMap = new HashMap();
		
	
	/*  ArrayList<Dog> list = new ArrayList<Dog>();

      list.add(new Dog("Shaggy",3));
      list.add(new Dog("Lacy",2));
      list.add(new Dog("Roger",10));
      list.add(new Dog("Tommy",4));
      list.add(new Dog("Tammy",1));*/
	
	//	Map<Integer, Dog> hashMap = new TreeMap<Integer, Dog>();
		Dog d1 = new Dog("red");
		Dog d2 = new Dog("black");
		Dog d3 = new Dog("white");
		Dog d4 = new Dog("green");
		
		hashMap.put(20, d3);
		hashMap.put(10, d1);
		hashMap.put(15, d2);	
		hashMap.put(20, d4); 

		//print size
		System.out.println(hashMap.size());
		
		
		for (Entry<Integer, Dog> intval1 : hashMap.entrySet()) {
			System.out.println(intval1.toString() );
			}
		
		//loop HashMap
		for (Dog intval : hashMap.values()) {
		System.out.println(intval.color);
		}
		for (Integer keyObj : hashMap.keySet()) {
			System.out.println(keyObj.toString() );
			
			
			
			/*for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());*/
		}
	}
}

Open in new window


if i comment and keep HashMap alone as above getting errors as below
Type mismatch: cannot convert from element type Object to Map.Entry<Integer,Dog>
please advise
ozoCommented:
If you comment our all the HashMap code, and keep only the list code:
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.Collections;
class Dog  implements Comparable<Dog> {

	String color;
 

	Dog(String c) {

	    color = c;

	}

	public Dog(String string, int i) {
	    // TODO Auto-generated constructor stub
	}

	public String toString(){  

	    return color + " dog22";

	}
	public int compareTo(Dog compareDog) {
	    return this.color.compareTo(compareDog.color);
	}
};
public class TestTreeMap5{
public static void main(String[] args) {
    //        TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();
        Dog d1 = new Dog("red");
	Dog d2 = new Dog("black");
	Dog d3 = new Dog("white");
	Dog d4 = new Dog("green");
	/*
	treeMap.put(d3, 20);
	treeMap.put(d1, 10);
	treeMap.put(d2, 15);	
	treeMap.put(d4, 20); 

	//print size
	System.out.println(treeMap.size());
		
	//loop treeMap
	for (Dog keyObj : treeMap.keySet()) {
	    System.out.println(keyObj.toString() );
	}
	*/
      ArrayList<Dog> list=new ArrayList<Dog>();
      list.add(d1);
      list.add(d2);
      list.add(d3);
      list.add(d4);
      Collections.sort(list);
      for (Dog keyObj : list ){
	  System.out.println(keyObj.color );
      }
}

}

Open in new window

You should get
black
green
red
white

If you comment  out all the list code, and leave only the treemap code
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.Collections;
class Dog  implements Comparable<Dog> {

	String color;
 

	Dog(String c) {

	    color = c;

	}

	public Dog(String string, int i) {
	    // TODO Auto-generated constructor stub
	}

	public String toString(){  

	    return color + " dog22";

	}
	public int compareTo(Dog compareDog) {
	    return this.color.compareTo(compareDog.color);
	}
};
public class TestTreeMap5{
public static void main(String[] args) {
        TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();
        Dog d1 = new Dog("red");
	Dog d2 = new Dog("black");
	Dog d3 = new Dog("white");
	Dog d4 = new Dog("green");

	treeMap.put(d3, 20);
	treeMap.put(d1, 10);
	treeMap.put(d2, 15);	
	treeMap.put(d4, 20); 

	//print size
	System.out.println(treeMap.size());
		
	//loop treeMap
	for (Dog keyObj : treeMap.keySet()) {
	    System.out.println(keyObj.toString() );
	}
			/*
      ArrayList<Dog> list=new ArrayList<Dog>();
      list.add(d1);
      list.add(d2);
      list.add(d3);
      list.add(d4);
      Collections.sort(list);
      for (Dog keyObj : list ){
	  System.out.println(keyObj.color );
      }
			*/
}

}

Open in new window

You should get
4
black dog22
green dog22
red dog22
white dog22
zzynxSr. Software engineerCommented:
if i comment and keep HashMap alone as above getting errors as below
Type mismatch: cannot convert from element type Object to Map.Entry<Integer,Dog>
You'd better always tell us on what line you get the error.
gudii9Author Commented:
i am getting many lines including 37, 42 etc as attached
lineNbr.png
gudii9Author Commented:
If you comment  out all the list code, and leave only the treemap code

line 49 has ArrayList again in the code right?
gudii9Author Commented:
In a HashMap it does that using "hashCode" - it's like the author's name or the code on the back of a book in a library.  It tells the HashMap which shelf to put the book on and when it goes looking for it again, where to find it.

It also uses "equals" to decide when you go to add a new book to the library - do we already have a copy of this book or not?

Since HashMap is like library and Objects are like Books in library and equals() and hashCode() methods helps to find and put the books in right shelf, does not hashCode() and equals() needs to be implemented in HashCode class( ie TestTreeMap5 in my case) rather than in Dog object class. please advise?
gudii9Author Commented:
import java.util.ArrayList;
import java.util.Collections;


public class TestTreeMap5{
public static void main(String[] args) {
    //        TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();
        Dog d1 = new Dog("red");
	Dog d2 = new Dog("black");
	Dog d3 = new Dog("white");
	Dog d4 = new Dog("green");
	/*
	treeMap.put(d3, 20);
	treeMap.put(d1, 10);
	treeMap.put(d2, 15);	
	treeMap.put(d4, 20); 

	//print size
	System.out.println(treeMap.size());
		
	//loop treeMap
	for (Dog keyObj : treeMap.keySet()) {
	    System.out.println(keyObj.toString() );
	}
	*/
      ArrayList<Dog> list=new ArrayList<Dog>();
      list.add(d1);
      list.add(d2);
      list.add(d3);
      list.add(d4);
      Collections.sort(list);
      for (Dog keyObj : list ){
	  System.out.println(keyObj.color );
      }
}

}

Open in new window


above code gives error at linev31 as below

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (ArrayList<Dog>). The
 inferred type Dog is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>

please advise
zzynxSr. Software engineerCommented:
Your TestTreeMap5 code looks correct.
But are you sure your Dog class is? It should implement the Comparable interface.
Can you please double check that is the case?

With this Dog code, I don't have that error:
class Dog  implements Comparable<Dog> {

    String color;


    Dog(String c) {

        color = c;

    }

    public Dog(String string, int i) {
        // TODO Auto-generated constructor stub
    }

    public String toString(){

        return color + " dog22";

    }
    public int compareTo(Dog compareDog) {
        return this.color.compareTo(compareDog.color);
    }
};

Open in new window


does not hashCode() and equals() needs to be implemented in HashCode class
No! (What else can I say? It should be implemented by the items you put in the library)
gudii9Author Commented:
import java.util.ArrayList;
import java.util.Collections;


public class TestTreeMap5{
public static void main(String[] args) {
    //        TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();
        Dog d1 = new Dog("red");
	Dog d2 = new Dog("black");
	Dog d3 = new Dog("white");
	Dog d4 = new Dog("green");
	/*
	treeMap.put(d3, 20);
	treeMap.put(d1, 10);
	treeMap.put(d2, 15);	
	treeMap.put(d4, 20); 

	//print size
	System.out.println(treeMap.size());
		
	//loop treeMap
	for (Dog keyObj : treeMap.keySet()) {
	    System.out.println(keyObj.toString() );
	}
	*/
      ArrayList<Dog> list=new ArrayList<Dog>();
      list.add(d1);
      list.add(d2);
      list.add(d3);
      list.add(d4);
      Collections.sort(list);
      for (Dog keyObj : list ){
	  System.out.println(keyObj.color );
      }
}

}

Open in new window


class Dog  implements Comparable<Dog> {

    String color;


    Dog(String c) {

        color = c;

    }

    public Dog(String string, int i) {
        // TODO Auto-generated constructor stub
    }

    public String toString(){

        return color + " dog22";

    }
    public int compareTo(Dog compareDog) {
        return this.color.compareTo(compareDog.color);
    }
};

Open in new window


above code finally generated below output

black
green
red
white
gudii9Author Commented:
How to do it using TreeMap not with ArrayList.

I see all TreeMap related code is commented except ArrayList and Collections.sort() is there. please advise

ArrayList<Dog> list=new ArrayList<Dog>();
      list.add(d1);
      list.add(d2);
      list.add(d3);
      list.add(d4);
      Collections.sort(list);
      for (Dog keyObj : list ){
        System.out.println(keyObj.color );
zzynxSr. Software engineerCommented:
How to do it using TreeMap
public class TestTreeMap5{
    public static void main(String[] args) {
        TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();
        Dog d1 = new Dog("red");
        Dog d2 = new Dog("black");
        Dog d3 = new Dog("white");
        Dog d4 = new Dog("green");

        treeMap.put(d3, 20);
        treeMap.put(d1, 10);
        treeMap.put(d2, 15);
        treeMap.put(d4, 20);

        //print size
        System.out.println(treeMap.size());

        //loop treeMap
        for (Dog keyObj : treeMap.keySet()) {
            System.out.println(keyObj.toString() );
        }
    }
}

Open in new window

and with your Dog class unchanged, this outputs:

4
black dog22
green dog22
red dog22
white dog22

as expected.

And when you negate the result of your compareTo() method:
public int compareTo(Dog compareDog) {
        return -this.color.compareTo(compareDog.color);
}

Open in new window


you get (again as expected):
4
white dog22
red dog22
green dog22
black dog22
gudii9Author Commented:
import java.util.TreeMap;

public class TestTreeMapAlone{
    public static void main(String[] args) {
        TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();
        Dog d1 = new Dog("red");
        Dog d2 = new Dog("black");
        Dog d3 = new Dog("white");
        Dog d4 = new Dog("green");

        treeMap.put(d3, 20);
        treeMap.put(d1, 10);
        treeMap.put(d2, 15);
        treeMap.put(d4, 20);

        //print size
        System.out.println(treeMap.size());

        //loop treeMap
        for (Dog keyObj : treeMap.keySet()) {
            System.out.println(keyObj.toString() );
        }
    }
}

Open in new window

above code produced below results successfully
black dog22
green dog22
red dog22
white dog22
gudii9Author Commented:
import java.util.TreeMap;

public class TestTreeMapAlone{
    public static void main(String[] args) {
        TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();
        Dog d1 = new Dog("red");
        Dog d2 = new Dog("black");
        Dog d3 = new Dog("white");
        Dog d4 = new Dog("green");

        treeMap.put(d3, 20);
        treeMap.put(d1, 10);
        treeMap.put(d2, 15);
        treeMap.put(d4, 20);

        //print size
        System.out.println(treeMap.size());

        //loop treeMap
        for (Dog keyObj : treeMap.keySet()) {
            System.out.println(keyObj.toString() );
        }
    }
}

Open in new window


class Dog  implements Comparable<Dog> {

    String color;


    Dog(String c) {

        color = c;

    }

    public Dog(String string, int i) {
        // TODO Auto-generated constructor stub
    }

    public String toString(){

        return color + " dog22";

    }
    /*public int compareTo(Dog compareDog) {
        return this.color.compareTo(compareDog.color);
    }*/
    
    public int compareTo(Dog compareDog) {
        return -this.color.compareTo(compareDog.color);
}

};

Open in new window


when i negate i did get reverse order.

4
white dog22
red dog22
green dog22
black dog22
gudii9Author Commented:
one question in my mind in above TestTreeMapAlone.java, TestTreeMap5.java both using below Dog object with compareTo() method alone without equals() and hashCode() methods. why we were not forced to use equals() and hashCode() methods here. Sometimes we are forced to use equals() and hashCode() methods as seen in other examples. please advise on which scenarios compareTo() method is sufficient and which scenarios along with compareTo() we need to implement equals() and hashCode() and which scenarios we need to implement equals() and hashCode() without compareTo() method.
class Dog  implements Comparable<Dog> {

    String color;


    Dog(String c) {

        color = c;

    }

    public Dog(String string, int i) {
        // TODO Auto-generated constructor stub
    }

    public String toString(){

        return color + " dog22";

    }
    /*public int compareTo(Dog compareDog) {
        return this.color.compareTo(compareDog.color);
    }*/
    
    public int compareTo(Dog compareDog) {
        return -this.color.compareTo(compareDog.color);
}

};

Open in new window

zzynxSr. Software engineerCommented:
When sorting is involved (TreeMap or calling sort()) => compareTo()
When hashing is involved (HashMap) => equals() and hashCode()

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
zzynxSr. Software engineerCommented:
But, I suggest you close this question for now, since you asked that last question also in a new thread (http://www.experts-exchange.com/Programming/Languages/Java/Q_28664164.html)
gudii9Author Commented:
sure
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.