Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

HAshmap class

Hi,

import java.util.HashMap;


public class Marks {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashMap<String, Integer> marks=new HashMap<String,Integer>();
		marks.put("aa",10);
		marks.put("ba",15);
		marks.put("Aa",13);
		marks.put("Ba",16);
		System.out.println("size is"+marks.size());
		if (marks.containsKey("aa")) {
				marks.remove("aa");
		}
		
		System.out.println("size is"+marks.size());
		
		
	}

}

Open in new window


i tried above example.

why we canot use integer but rather using Integer as below
HashMap<String, Integer> marks=new HashMap<String,Integer>();

also which interfaces have put method?
 can i interchange positions like
HashMap<Integer, String> marks=new HashMap<Integer,String>();

how it is advantageous, disadvatageos to use compared to TreeMap.

please advice
SOLUTION
Avatar of Mark Bullock
Mark Bullock
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> Why we canot use integer but rather using Integer as below
Because java simply doesn't allow you to use a primitive type (which int is) as the type of the Map's key and value

>> also which interfaces have put method?
the Interface Map<K,V> with implementing sub classes AbstractMap, Attributes, AuthProvider, ConcurrentHashMap, ConcurrentSkipListMap, EnumMap, HashMap, Hashtable, IdentityHashMap, LinkedHashMap, PrinterStateReasons, Properties, Provider, RenderingHints, SimpleBindings, TabularDataSupport, TreeMap, UIDefaults, WeakHashMap

>> can i interchange positions
No. The first is your key type, the second is your value type.
Depending on what "search" operation you need the map for, you have to use one or the other.
E.g.
If you need to know the address of a certain Person, on your map
Map<Person, Address> personToAddress = ...

Open in new window

you perform a get call with the person as parameter
personToAddress.get(person) 

Open in new window

to get the address.
If in your program you frequently need to search a Person given a certain address, you'd better use a map
Map<Address, Person> addressToPerson = ...

Open in new window

Avatar of gudii9

ASKER

HashMap  
provides constant-time performance for the basic operations (get and put).
you may have to implement equals method for the key class.
faster if you don't need the keys sorted

TreeMap
provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.
you may have to implement Comparable Interface for the key class.
is sorted

Can you please elaborate on this. I think i did not get it.
Constant-time means the time for a HashMap lookup will not increase as you add more items to it.
If the class you use for the key does not have an equals method, you may have to implement it.
Avatar of gudii9

ASKER

TreeMap
provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

what it means by above statement. Why we need to implement equals for HashMap key where as comparable for TreeMap.

Please advise
TreeMap entries are ordered, HashMap entries are unordered.
Avatar of gudii9

ASKER

TreeMap entries are ordered, HashMap entries are unordered.

if it is unordered we do not need to implement equals but do we still need to implement comparable. please advise
It's not necessary for HashMap because you're not ordering them and so don't need to compare for less than or greater than.
Avatar of gudii9

ASKER

but do we still need to implement comparable for HashMap. why we need to implement comaparable for HashMap and not for Tree map. Any links, resources on this topic. please advise??
You don't need to implement comparable for HashMap.
You need to implement comparable for TreeMap because you are comparing the keys for <, =, >

This page gives an overview with some sample code.
http://java.dzone.com/articles/hashmap-vs-treemap-vs
Avatar of gudii9

ASKER

TreeMap is implemented based on red-black tree structure, and it is ordered by the key.

what it mean by red-black tree structure,

please advise
It's an algorithm to organize binary tree data so the tree has the smallest height.
It can be searched in O(log n) time.
Wikipedia has a good explanation with diagrams.
Avatar of gudii9

ASKER

import java.util.HashMap;



public class TestHashMap {
	public static void main(String[] args) {
		HashMap hashMap = new HashMap();
		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 : s) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());
		}
	}
}

Open in new window


compiler not happy about Entry. please advise
In line 22, replace    : s    with    : hashMap
>> compiler not happy about Entry. please advise
You use a variable 's' that is nowhere defined.
I would expect you to be able to find and fix that yourself.
Avatar of gudii9

ASKER

Multiple markers at this line
      - Entry cannot be resolved
       to a type
      - s cannot be resolved to a
       variable

eclipse gave above error which does not gave me clue that s needs to be replaced by hashMap. But i should have focussed on second line rather than first line which would have resolved part of the issue

Even after repacing compiler complaining as about Entry and it suggested multiple imports(around 50) as attached. I wonder which one to select. please advise
Entry.jpg
You can iterate over your HashMap like this:
for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {

Open in new window

Avatar of gudii9

ASKER

i am gettin below error

Type mismatch: cannot convert from element type Object to Map.Entry<Dog,Integer>

i tried as below

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



public class TestHashMap {
	public static void main(String[] args) {
		HashMap hashMap = new HashMap();
		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 : s) {
			//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


please advise
Change your hashMap declaration to this:
            HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
Avatar of gudii9

ASKER

this worked

package jdbc;
import java.util.HashMap;
import java.util.Map;



public class TestHashMap {
      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 : s) {
                  //System.out.println(entry.getKey().toString() + " - " + entry.getValue());
                  
                  for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
                  System.out.println(entry.getKey().toString() + " - " + entry.getValue());
            }
      }
}


i got

4
white dog - 20
black dog - 15
red dog - 10
white dog - 5
Avatar of gudii9

ASKER

i still did not understand why below do not works

package jdbc;
import java.util.HashMap;
import java.util.Map;



public class TestHashMap {
      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 : s) {
            System.out.println(entry.getKey().toString() + " - " + entry.getValue());
                  
                  /*for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
                  System.out.println(entry.getKey().toString() + " - " + entry.getValue());*/
            }
      }
}

please advise
You have to specify what objects you'll store in the HashMap.

HashMap is a generic class. You can read a good tutorial here.
https://docs.oracle.com/javase/tutorial/java/generics/types.html
>> i still did not understand why below do not work

I you write
HashMap hashMap = new HashMap();

Open in new window

your hashMap variable is known as a HashMap<Object, Object>, a HashMap that has an Object instance as key ànd value.
Hence, the message:
Type mismatch: cannot convert from element type Object to Map.Entry<Dog,Integer>
on this line:
for (Map.Entry<Dog, Integer> entry : hashMap.entrySet())

Open in new window


hashMap.entrySet() returns a collection of Object instances.
You try to assign that Object instances to instances of Map.Entry<Dog, Integer>.
This leads to the error:
Type mismatch: cannot convert from element type Object to Map.Entry<Dog,Integer>
- Entry cannot be resolved to a type
- s cannot be resolved to a variable

Those two errors are not linked.
The first tells you you can't use Entry but should replace it by Map.Entry
The second tells you that the (what seems to be a) variable 's' is nowhere defined. (Because you meant 'hashMap')
Avatar of gudii9

ASKER

package jdbc;
import java.util.HashMap;
import java.util.Map;



public class TestHashMap {
	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 : s) {
		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


so to make above code to work without using commented code of generics which is bit confusing
Avatar of gudii9

ASKER

i tried as below

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



public class TestHashMap {
	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

getting error as below

Multiple markers at this line
      - Map.Entry is a raw type. References to generic type Map<K,V>.Entry<K,V> should be
       parameterized
      - Can only iterate over an array or an instance of java.lang.Iterable

please advise
Avatar of gudii9

ASKER

i did not understand meaning of below lines. please advise

             
HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>(); //defining hashmap collection which has dog as value and integer as key right?


for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {//why Map used at beginning and hashMap at the end also why Entry at beginning and entrySet at the end
                  System.out.println(entry.getKey().toString() + " - " + entry.getValue());//why using entry but not entrySet.

Open in new window

//defining hashmap collection which has dog as value and integer as key right?
INcorrect. Dog as key, Integer as value.

//why Map used at beginning and hashMap at the end also why Entry at beginning and entrySet at the end
I don't understand what you mean

why using entry but not entrySet.
You iterate over an EntrySet (a set of Entry instances)
Once you are inside the iteration loop you deal with Entry's
In pseudo code:
for (each instance that is part of the set) {
     deal with the instance of the set
}

Open in new window

In Java you can write an iteration like this:
for ( instanceType variableName : collection) { 
... 
}

Open in new window

E.g.  
for ( Integer myInt : integerList) {
    // use myInt
}

Open in new window

- myInt is the variable you can use inside the loop
- integerList is variable representing the collection (a list in this case) containing Integers

Let's consider your case:

for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
  ...  use entry
}

Open in new window


- entry is the variable you can use inside the loop. Its type is "Map.Entry<Dog, Integer>", it's an entry of a map which has a Dog as key and an Integer as value.
- the collection (in this case a set) containing those kind of entries is what you get when you call the method entrySet() on your "hashMap" variable.

I hope that is clear now
Avatar of gudii9

ASKER

for ( Integer myInt : integerList) {
    // use myInt
}


above is clear.

below is bit confusing still

for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
  ...  use entry
}


- entry is the variable you can use inside the loop. Its type is "Map.Entry<Dog, Integer>", it's an entry of a map which has a Dog as key and an Integer as value.//this is similar to Integer myInt part right?and hashMap.entrySet() similar to integerList right?
- the collection (in this case a set) containing those kind of entries is what you get when you call the method entrySet() on your "hashMap" variable.
Avatar of gudii9

ASKER

- the collection (in this case a set) containing those kind of entries is what you get when you call the method entrySet() on your "hashMap" variable.

above line is not clear yet. please advise
Avatar of gudii9

ASKER

Dog d1 = new Dog("red");//are we setting the value here in below four lines??
            Dog d2 = new Dog("black");
            Dog d3 = new Dog("white");
            Dog d4 = new Dog("white");
            
            hashMap.put(d1, 10);//are we setting key here in below four lines?..but i wonder why we are again using d1, d2, d3, d4?
            hashMap.put(d2, 15);
            hashMap.put(d3, 5);
            hashMap.put(d4, 20);
Avatar of gudii9

ASKER

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



public class TestHashMap {
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());
		
		
		for (Entry<Dog, Integer> intval1 : hashMap.entrySet()) {
			System.out.println(intval1.toString() );
			}
		
		//loop HashMap
		for (Integer intval : hashMap.values()) {
		System.out.println(intval.toString() );
		}
		for (Dog keyObj : hashMap.keySet()) {
			System.out.println(keyObj.color );
			
			
			
			/*for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());*/
		}
	}
}

Open in new window

worked
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

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


this also worked with
4
white dog22 - 5
black dog22 - 15
white dog22 - 20
red dog22 - 10


so entrySet is like table row(imaginary table row with key and value as first and second cell values). Once we get that entrySet row with both key and value into Entry then we are iterating that entry right. Please correct me if my understanding is wrong.

my above program bit weird because it has value as Int and key as Dog object which usually otherway right.

please advise
Do you want it otherway?  What is usual?  Do you want it usual?
Yes you usually have a simple key like an int or String
Why did you choose to use Dog as key?  What is a Dog?   What do you want to do with the map?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanx 4 axxepting