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
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.

Mark BullockQA EngineerCommented:
You have to use Integer because Integer is a class. int is a datatype.

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
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
can i interchange positions like
HashMap<Integer, String> marks=new HashMap<Integer,String>();
It depends on what you are putting in there, but I would say generally, NO.

The first listed class name is the class used as the "key" in the map, and the second is the class that is the "value". You can easily/efficiently find the "value" associated with a particular "key" but you can't easily find a "key" based on a "value", so that is the main reason to choose which is your key and which is your value.

An example: say you have a class that holds details about an employee (such as name, age, position, telephone number, etc) and you identify employees with an "employee id" which is just a number. If you want to store this is information in a Map, you would make the numeric employee id the "key" and the class holding the details as the "value", ie. Map<Integer, EmployeeDetails> employees = new HashMap<Integer, EmployeeDetails>();   It wouldn't make sense to change the key/value around in this case, because it would mean that you would need an instance of the EmployeeDetails class to "look up" their employee id.... not a very useful scenario.
0
zzynxSr. Software engineerCommented:
>> 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

0
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

gudii9Author Commented:
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.
0
Mark BullockQA EngineerCommented:
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.
0
gudii9Author Commented:
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
0
ozoCommented:
TreeMap entries are ordered, HashMap entries are unordered.
0
gudii9Author Commented:
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
0
Mark BullockQA EngineerCommented:
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.
0
gudii9Author Commented:
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??
0
Mark BullockQA EngineerCommented:
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
0
gudii9Author Commented:
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
0
Mark BullockQA EngineerCommented:
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.
0
gudii9Author Commented:
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
0
Mark BullockQA EngineerCommented:
In line 22, replace    : s    with    : hashMap
0
zzynxSr. Software engineerCommented:
>> 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.
0
gudii9Author Commented:
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
0
Mark BullockQA EngineerCommented:
You can iterate over your HashMap like this:
for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {

Open in new window

0
gudii9Author Commented:
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
0
Mark BullockQA EngineerCommented:
Change your hashMap declaration to this:
            HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
0
gudii9Author Commented:
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
0
gudii9Author Commented:
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
0
Mark BullockQA EngineerCommented:
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
0
zzynxSr. Software engineerCommented:
>> 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>
0
zzynxSr. Software engineerCommented:
- 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')
0
gudii9Author Commented:
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
0
gudii9Author Commented:
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
0
gudii9Author Commented:
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

0
zzynxSr. Software engineerCommented:
//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

0
zzynxSr. Software engineerCommented:
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
0
gudii9Author Commented:
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.
0
gudii9Author Commented:
- 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
0
gudii9Author Commented:
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);
0
gudii9Author Commented:
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
0
ozoCommented:
Where is Dog defined?
Dog d1 = new Dog("red");//are we setting the value here in below four lines??
We are setting the value of d1

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?
We are using the value of d1 as the key.  Presumably because we want to use a "red" Dog for the key, and d1 was set to "red"
0
gudii9Author Commented:
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
0
ozoCommented:
Do you want it otherway?  What is usual?  Do you want it usual?
0
Mark BullockQA EngineerCommented:
Yes you usually have a simple key like an int or String
0
ozoCommented:
Why did you choose to use Dog as key?  What is a Dog?   What do you want to do with the map?
0
zzynxSr. Software engineerCommented:
- 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

In these lines of code
for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
  ...  use entry
}

Open in new window

you iterate over the entries of your map.
Calling the method entrySet() on your map gives you the entries of your map.
In your case such an entry has a Dog instance as key and an Integer as value.
That's how you read that line:
for (Map.Entry<Dog, Integer> entry : hashMap.entrySet())

Open in new window


In English it reads as: For each entry in my map do ...

The 4 lines of
Dog d1 = new Dog("red");

Open in new window

create your 4 Dog instances (you gonna use them as the keys of your map)
With the 4 lines:
hashMap.put(d1, 10);

Open in new window

you fill up your map.
In the above line, you use the d1 variable (you created in the previous line) as the key and you put 10 as the value.

Your map now looks like:
key --->  value
--------------------
d1  --->   10
d2  --->   15
d3  --->     5
d4  --->   20
0

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:
Thanx 4 axxepting
0
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.