Hashmap problem

Hi I am getting only last value from hashmap
codes are below.
Then I used iterator and getting
Required string is null or empty
jsp code
<bean efine id="a" name="b" property="c"/>
<bean efine id="e" name="b" property="d"/>
<%
java.util.HashMap params = new java.util.HashMap();
params.put("a",a);
params.put("b",e);
session.setAttribute("paramsName", params);
%>
action classs code
Map paramsName = new HashMap();
paramsName=(HashMap)session.getAttribute("paramsName");
if (paramsName!=null)
{ Iterator pIter = paramsName.keySet().iterator();
while(pIter.hasNext()){
a=(String)pIter.next();}

How about the following:
create a class with instance variables of ints to be your counters:
public int inserts = 0;
public int updates = 0;
public int deletes = 0;name the class something... Tally maybe.
Might be nice to put in methods to increment each like so:
public void incrementInserts() {
      inserts ++;
}and so on for the other instance variables.
then you create one of these and increment its values appropriately, then put it in the hash.
Code would look something like this:
Map myMap = new HashMap();
while ( logfileIterator.hasNext()) {
     String tableName = null;
     boolean lineIsDelete;
     boolean lineIsInsert;
     boolean lineIsUpdate;
      /* put your code here to analyze the line to find out what the table name is,
          whether it's a delete, insert or update, and set above vars accordingly */
      Tally myTally = null;
      if (myMap.containsKey(tableName)) {
                   /* code for second and subsequent times you see this table name*/
                 myTally = (Tally) myMap.get(tableName);
      } else {
                 /* code for first time you see this table name */
                 myTally = new Tally();
                 myMap.put (tableName, myTally);
      if (lineIsDelete) myTally.incrementDeletes();
      /* or if you didn't write that method you could just use [u]myTally.deletes++;[/u] */
      if (lineIsInsert) myTally.incrementInserts();
      if (lineIsUpdate) myTally.incrementUpdates();
}

Similar Messages

  • Follow up on XPATH HashMap problem

    Hi,
    I got some great help before on this & am hoping for a little direction. I have a class that calculates the tax from an xml like below:
    <Taxes>
         <Tax TaxCode='code1' Amount='101.00'/>
         <Tax TaxCode='code2' Amount='102.00'/>
         <Tax TaxCode='code3' Amount='103.00'/>
         <Tax TaxCode='code4' Amount='104.00'/>
         <Tax TaxCode='code5' Amount='105.00'/>
    </Taxes>Now, my method below, gets the last 3 values and sums them and applies the code "XT" to it & returns a HashMap that looks like:
    {code1 = 101.00, code = 102. 00, XT = 312.00}.
    public static HashMap getTaxAmounts(String xml) throws Exception {
              HashMap taxes = new HashMap();
              DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true); // never forget this!
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document doc = builder.parse(xml);
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile("//Tax/@TaxCode");
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            XPathExpression expr1 = xpath.compile("//Tax/@Amount");
            Object result1 = expr1.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes1 = (NodeList) result1;
            for ( int i = 0; i < nodes1.getLength() && (i<2); i++) {
                   taxes.put( nodes.item(i).getNodeValue(), nodes1.item(i).getNodeValue());
                    if( nodes1.getLength() >= 3){
                        float total = 0.00f;
                        for ( int i = 2; i < nodes1.getLength(); i++) {
                                total += Float.parseFloat(nodes1.item(i).getNodeValue());
                        String xt = nodes.item(2).getNodeValue();
                        xt = "XT";
                        taxes.put( xt, total);
           return taxes;     
    /code]
    all that's fine - but now I have to replace the tags in the original XML file so that they look like:<Taxes>
    <Tax TaxCode='code1' Amount='101.00'/>
    <Tax TaxCode='code2' Amount='102.00'/>
    <Tax TaxCode='XT' Amount='312.00'/>
    </Taxes>
    any odeas how I would this???

    Hi, John. I can address one of your questions here.
    However, the picture was slightly cropped at the top and it also had 2 very small borders on the left and right, being printed in landscape.
    A standard digital camera image is proportioned 4:3 (1.33:1). That doesn't match the 6:4 ratio of your paper's dimensions (1.5:1), so unless you opt either to distort the image or crop it, it can't be an exact fit on the paper.
    In the toolbar at the top of iPhoto's Edit view is a pull-down menu above the word "Constrain". You use that menu to specify standard proportions for printing the image. Select "4x6 (Postcard)", and you will see superimposed on the picture a rectangle that has those proportions. What's inside the rectangle looks normal, signifying that it will be printed; what's outside the rectangle is pale and muted, because it will be cropped away when you print. Place your cursor anywhere inside the rectangle, hold the mouse button down and drag, to move the rectangle and change what's included within the print boundary.
    The fact that your printed picture was both cropped and slightly reduced in size (creating the small left and right borders) suggests to me that your printer may not be capable of borderless printing, or that there is a setting for borderless prints you're overlooking somewhere. Since the contents of both the Print and Page Setup dialog boxes are governed by the printer's own driver software, and there's no "borderless" setting anywhere within iPhoto, I think you'll need to review the printer's documentation and/or online help files carefully to see whether you're overlooking something in one of those dialog boxes.

  • JPA 2.0 CriteriaQuery problem

    Hi all,
    I am creating JPA 2.0 web application using Spring 2.5. I have one entity:
    package data;
    @Entity
    public class NewEntity implements Serializable {
    }a JPA controller for it
    public class NewEntityJpaController {
         public int getNewEntityCount() {
              EntityManager em = getEntityManager();
              try {
                   CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
                   Root<NewEntity> rt = cq.from(NewEntity.class);
                   cq.select(em.getCriteriaBuilder().count(rt));
                   Query q = em.createQuery(cq);
                   return ((Long) q.getSingleResult()).intValue();
              } finally {
                   em.close();
    }and a Spring controller:
    public class NewAbstractController extends AbstractController {
         jpa.NewEntityJpaController     c     = new jpa.NewEntityJpaController();
        public NewAbstractController() {
        protected ModelAndView handleRequestInternal(
                HttpServletRequest request,
                HttpServletResponse response) throws Exception {
            ModelAndView     mv     = new ModelAndView("/index");
              mv.addObject("data", c.getNewEntityCount());
              return mv;
    }But when I access web page, I get the following exception:
    java.lang.IllegalArgumentException: The type [null] is not the expected [EntityType] for the key class [class data.NewEntity]Trace:
    java.lang.IllegalArgumentException: The type [null] is not the expected [EntityType] for the key class [class data.NewEntity].
            at org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl.entity(MetamodelImpl.java:152)
            at org.eclipse.persistence.internal.jpa.querydef.AbstractQueryImpl.from(AbstractQueryImpl.java:97)
            at jpa.NewEntityJpaController.getNewEntityCount(NewEntityJpaController.java:131)
            at web.controllers.NewAbstractController.handleRequestInternal(NewAbstractController.java:28)
    ...

    Same problem here. I'm using Oracle as back-end. Same error...
    Using the APP schema in java DB works... As I can see the code generated by Netbeans looks the same.
    Anyone knows how to fix it? (some linked hashmap problem it seams)
    10x
    Florin POP

  • Servlet side Cache implementation - need cache (updateable, portable) in Servlet

    Hi Guys,
              Any ideas on implementing an updateable cache on a servlet. The problem is
              that
              it must be updateable (I must be able to tell it to update itself whenever a
              welldefined
              event occurs), and it must work in a cluster environment, and I would prefer
              it to
              be J2EE portable.
              I know I can poll from the servlet - but this isn't the most elegant
              approach.
              My servlet needs to do some really fast security/auditing, but I don't want
              it to
              always do something like an EJB lookup. I can quite easily cache what I
              need
              in the hashmap - problem is updateing it and also having it work in a
              clustered
              environ.
              Any other ideas appreciated,
              Jon
              

    ejp wrote:
    Of course it is. That's how any Map behavesWhen a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations. I meant, the mapping doesnt prevent the key from getting discarded cause it is a weakreference.
    No: it's out of your control, but it's within the garbage collector's control. That is the purpose of the class.You aint talking about the situation written in this email. So if it is out of control, your suggestion about weakhashmap isn't gonna work. Out of control in the sense, it doesnt treat a key which was recently accessed any different from anything which wasn't accessed for a long time.
    Because by choosing a key that will get garbage-collected at the time of interest to you, you ensure that the WeakHashMap will drop the corresponding value at the same time as the key is GC'd.Not realted to the problem above. Summarily WeakHashmap is no good for the above scenario.

  • Using a hashmap for caching -- performance problems

    Hello!
    1) DESCRIPTION OF MY PROBLEM:
    I was planing to speed up computations in my algorithm by using a caching-mechanism based on a Java HashMap. But it does not work. In fact the performance decreased instead.
    My task is to compute conditional probabilities P(result | event), given an event (e.g. "rainy day") and a result of a measurement (e.g. "degree of humidity").
    2) SITUATION AS AN EXCERPT OF MY CODE:
    Here is an abstraction of my code:
    ====================================================================================================================================
    int numOfevents = 343;
    // initialize cache for precomputed probabilities
    HashMap<String,Map<String,Double>> precomputedProbabilities = new HashMap<String,Map<String,Double>>(numOfEvents);
    // Given a combination of an event and a result, test if the conditional probability has already been computed
    if (this.precomputedProbability.containsKey(eventID)) {
    if (this.precomputedProbability.get(eventID).containsKey(result)) {
    return this.precomputedProbability.get(eventID).get(result);
    } else {
    // initialize a new hashmap to maintain the mappings
    Map<String,Double> resultProbs4event = new HashMap<String,Double>();
    precomputedProbability.put(eventID,resultProbs4event);
    // unless we could use the above short-cut via the cache, we have to really compute the conditional probability for the specific combination of the event and result
    * make the necessary computations to compute the variable "condProb"
    // store in map
    precomputedProbabilities.get(eventID).put(result, condProb);
    ====================================================================================================================================
    3) FINAL COMMENTS
    After introducing this cache-mechanism I encountered a severe decrease in performance of my algorithm. In total there are over 94 millions of combinations for which the conditional probabilities have to be computed. But there is a lot of redundancy in this set of feasible combinations. Basically it can be brought down to just about 260.000 different combinations that have to be captured in the caching structure. Therefore I expected a significant increase of the performance.
    What do I do wrong? Or is the overhead of a nested HashMap so severe? The computation of the conditional probabilities only contains basic operations.
    Only for those who are interested in more details
    4) DEEPER CONSIDERATION OF THE PROCEDURE
    Each defined event stores a list of associated results. These results lists include 7 items on average. To actually compute the conditional probability for a combination of an event and a result, I have to run through the results list of this event and perform an Java "equals"-operation for each list item to compute the relative frequency of the result item at hand. So, without using the caching, I would estimate to perform on average:
    7 "equal"-operations (--> to compute the number of occurences of this result item in a list of 7 items on average)
    plus
    1 double fractions (--> to compute a relative frequency)
    for 94 million combinations.
    Considering the computation for one combination (event, result) this would mean to compare the overhead of the look-up operations in the nested HashMap with the computational cost of performing 7 "equal' operations + one double fration operation.
    I would have expected that it should be less expensive to perform the lookups.
    Best regards!
    Edited by: Coding_But_Still_Alive on Sep 10, 2008 7:01 AM

    Hello!
    Thank you very much! I have performed several optimization steps. But still caching is slower than without caching. This may be due to the fact, that the eventID and results all share long common prefixes. I am not sure how this affects the computation of the values of the hash method.
    * Attention: result and eventID are given as input of the method
    Map<String,Map<String,Double>> precomputedProbs = new HashMap<String,Map<String,Double>>(1200);
    HashMap<String,Double> results2probs = (HashMap<String,Double>)this.precomputedProbs.get(eventID);
    if (results2Probs != null) {
           Double prob = results2Probs.get(result);
           if (prob != null) {
                 return prob;
    } else {
           // so far there are no conditional probs for the annotated results of this event
           // initialize a new hashmap to maintain the mappings
           results2Probs = new HashMap<String,Double>(2000);
           precomputedProbs.put(eventID,results2Probs);
    * Later, in case of the computation of the conditional probability... use the initialized map to save one "get"-operation on "precomputedProbs"
    // the variable results2probs still holds a reference to the inner HashMap<String,Double> entry of the HashMap  "precomputedProbs"
    results2probs.put(result, condProb);And... because it was asked for, here is the computation of the conditional probability in detail:
    * Attention: result and eventID are given as input of the method
    // the computed conditional probabaility
    double condProb = -1.0;
    ArrayList resultsList = (ArrayList<String>)this.eventID2resultsList.get(eventID);
    if (resultsList != null) {
                // listSize is expected to be about 7 on average
                int listSize = resultsList.size(); 
                // sanity check
                if (listSize > 0) {
                    // check if given result is defined in the list of defined results
                    if (this.definedResults.containsKey(result)) { 
                        // store conditional prob. for the specific event/result combination
                        // Analyze the list for matching results
                        for (int i = 0; i < listSize; i++) {
                            if (result.equals(resultsList.get(i))) {
                                occurrence_count++;
                        if (occurrence_count == 0) {
                            condProb = 0.0;
                        } else {
                            condProb = ((double)occurrence_count) / ((double)listSize);
                        // the variable results2probs still holds a reference to the inner HashMap<String,Double> entry of the HashMap  "precomputedProbs"
                        results2probs.put(result, condProb);
                        return condProb;
                    } else {
                        // mark that result is not part of the list of defined results
                        return -1.0;
                } else {
                    throw new NullPointerException("Unexpected happening. Event " + eventID + " contains no result definitions.");
            } else {
                throw new IllegalArgumentException("unknown event ID:"+ eventID);
            }I have performed tests on a decreased data input set. I processed only 100.000 result instances, instead of about 250K. This means there are 343 * 100K = 34.300K = 34M calls of my method per each iteration of the algorithm. I performed 20 iterations. With caching it took 8 min 5 sec, without only 7 min 5 sec.
    I also tried to profile the lookup-operations for the HashMaps, but they took less than a ms. The same as with the operations for computing the conditional probability. So regarding this, there was no additional insight from comparing the times on ms level.
    Edited by: Coding_But_Still_Alive on Sep 11, 2008 9:22 AM
    Edited by: Coding_But_Still_Alive on Sep 11, 2008 9:24 AM

  • Simple Problem with hashmap

    Hello,
    I am having a problem creating a hashmap--I am not sure what is going wrong, but here is the code I am using:
    import java.util.*;
    public class HashMap{
    public static void main(String args[]){
         HashMap myHashMap = new HashMap();
         myHashMap.put("one","1");
    When I go to compile I get this error:
    HashMap.java:6: cannot resolve symbol
    symbol : method put (java.lang.String,java.lang.String)
    location class HashMap
    myHashMap.put("one","1");
    ^
    If anyone could offer some help that would be great. Thanks!

    THANK YOU!
    I'm a newbie and this problem was driving me crazy also. I inadvertently created a HashMap.class. Once I deleted the class from the folder, all of my programs worked! (Duh!)

  • Problem in returning the object + reflection + hashMap + list

    Hi All,
    i am very new to java forums...
    i'm sorry to disturb you all.. i don't exaclty know how to raise a question in forums..
    Here my query is ::::
    i have xlsReader file,which will read the data from the xls file.
    after reading it,i am adding the contents of the xls sheet in to a Arraylist.
    then i've put the list contents in to an object array,
    then i'm invoking the getter and setter method of the javabean class.
    and i'm returning object,but object contains only the last data of the list,instead of whole contents in that object.
    the code is here,where am returnung the object.
    kindly do reply...
    Thanks in advance...:)
    public static Object setDynamicValue ( Method setter2, List columnData, Object obj2 , Method getter2 )
    Object val2=null;
    try {
    for ( int i = 0 ; i < columnData.size() ; i++ ) {
    Object obj[] =( Object [] )columnData.get(i);
    for ( int j = 0; j < obj.length; j++) {
    // System.out.println("column Data:pppp: :"+obj[j].toString());
    setter2.invoke(obj2, new Object[] {obj[j].toString() });
    val2 = getter2.invoke(obj2, new Object[0]);
    //System.out.println("output:::"+val2.toString());
    // return val2;
    System.out.println("#########################");
    }catch (IllegalAccessException e) {
    System.out.println("IllegalAccessException came :::"+e);
    } catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    System.out.println("IllegalArgumentException came :::"+e);
    e.printStackTrace();
    } catch (InvocationTargetException e) {
    System.out.println("InvocationTargetException came :::"+e);
    // TODO Auto-generated catch block
    e.printStackTrace();
    return val2;
    here,we are returning the object val2 , but its printing only the last data of the list
    Object o1 = setDynamicValue ( setter2, columnName ,columnData, obj2,getter2 );
    System.out.println("lastvalue of the list :"+o1);
    thanks...
    plz reply..

    You are getting only the last data of the list because you does not have any mechanism to hold other values.
    Check inf your code your the following code in the inner for loop (loop with index j)
    val2 = getter2.invoke(obj2, new Object[0]);
    Even if you are capturing some value into val2, it gets replaced next time the body of for loop runs. This way you are getting only the last data.
    If you want to capture all values use arraylist. Keep adding all values to arraylist and return it. While printing iterate over arraylist and print values.
    This is not a problem related to reflection or hashMap. Just the logic you have written is incorrect.

  • Problem in setting vector or string[] as the "value object" in hashmap

    Hey I am new to this forum.
    I am doing a project in which i need to store a array of strings as "value object" for a unique key in hashmap.
    as I populate the hashmap from external file according to key and setting the string[]. The hashmap is taking the value field same for each entry i.e the last field as i keep updating the same variable and then putting it into hashmap.
    Please give solution to my problem???
    if question not clear,please tell me- i will add more information
    Edited by: AnkitNahar on Apr 4, 2009 8:06 AM

    I tried using the method suggested by you...but it is of same case as using the string[].
    I need to loop the statements in which the hashmap is populating so cant change the variable names in the dd.put() statements. When the below code executes it shows the same set of string for both the keys, that was the problem i was facing with string[].
    here is the example with two entries....same thing in looping.
    HashMap<String,Set<String>> dd=new HashMap<String,Set<String>>();
    String word = "Hello";
    Set<String> alternativeWords = new HashSet<String>();
    alternativeWords.add("Hi");
    alternativeWords.add("Yo");
    dd.put(word, alternativeWords);
    alternativeWords.clear();
    alternativeWords.add("hey");
    word="yep";
    dd.put(word,alternativeWords);
    System.out.println(dd.get("Hello").toString());
    System.out.println(dd.get("yep").toString());

  • Jax-ws 2.1 - problems returning hashtable and hashmap

    Hi,
    We're developing a set of applications that communicate via web services.
    The company decided that to do this we should use jax-ws 2.1.
    Everything is going ok, its really easy to use, except for a web method that returns a java.util.Hashtable.
    In the endpoint there's no problem, it compiles and deploys to a tomcat 5.5 without a problem.
    The client can access the wsdl via url, download it and create the necessary files (we use netbeans 5.5 for this).
    We can invoke the method getConfig without a problem, but the object returned only has the java.lang.Object 's methods, not the java.util.Hastable 's .
    Endpoint:
    package xxx.cdc_pm_i;
    import java.util.Hashtable;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import javax.xml.bind.annotation.*;
    @WebService()
    public class cdc_pm_i{
    @WebMethod
    public Hashtable getConfig() {
    Hashtable<String,String> config = new Hashtable<String,String>();
         config.put("1","1");
         config.put("2","2");
    return config;
    Client:
    try { // Call Web Service Operation
    xxx.CdcPmIService service = new xxx.cdc_pm_i.CdcPmIService();
    xxx.cdc_pm_i.CdcPmI port = service.getCdcPmIPort();
    // TODO process result here
    xxx.cdc_pm_i.Hashtable result = port.getConfig();
    } catch (Exception ex) {
         ex.printStackTrace();
    I'm fairly unexperienced in Web Services and i have no idea why this works for any kind of return object (as long as its serializable) and has this problem with hashtables and hashmaps.
    Any idea on how to solve this?
    Thanks in advance,
    Rui

    Didn't find the solution for this, but any object that contains an Object in its methods / attributes had the same problems, so i just built my own table that only supports Strings and the problem was solved.
    If anyone knows why i had this problem and wants to share a solution, please do so.

  • I have problems with HashMap

    hello guys
    i have a problems whith this assignment.
    im usunig BlueJ
    its about a library has members and lists of the books available( a catalogue for viewing by members) and of the copies of
    these (for stock control purposes).
    information of a book (title, author, and ISBN), the title is a unique identifier.
    a book may have several copies, each with a unique stock number (an integer). a book may have no copies (if, for
    example, it has been added to the catalogue, but copies havent yet arrived.
    the library most be able to:
    - add a book to the catalogue for example when its newly published.
    - add a copy of a book to its stock when the library receives this item.
    - obtain a list of copies of a book, given its title.
    - obtain a String representation of the list of copies of a book, given its title; this should just be the title
    and list of stock numbers, for examble :( title, copies: 2000, 2001, 2002).
    now i cant make the HashMap for the stock items,
    is there anything wrong i have made or any suggestions to help me to continue my work?
    the two classes i have made so far:
    public class books
        private String title;
        private String author;
        private String ISBN;
        private int quantity;
        private int stockNumber;
        public books(String title, String author, String ISBN)
            this.title = title;
            this.author = author;
            this.ISBN = ISBN;
            //stock number satrts from 2000
            stockNumber = 1999;
        public int addquntity (int amount)
                quantity = quantity + amount;
                return quantity;
        // chang the quantity when costumer borrows a book from the library
        public int getBorowed()
            if(quantity > 0){
              quantity --;
            else{
                System.out.print("sorry the book is not avalible, try again later");
                return quantity;
        // chang the quantity when costumer rturnes a book to the library
        public void deliverBookBack()
            quantity++;
        public String toString()
            return title + " by " + author + ". ISBN = " + ISBN ;
        // change the stock number after adding any book to the library
        public int autoStockNumber()
            stockNumber ++;
            return stockNumber;
        public int getStockNumber()
            return  stockNumber;
    }======================================================
    import java.util.ArrayList;
    import java.util.HashMap;
    public class library
        private ArrayList<books> book;
        private ArrayList<members> member;
      // i coudnt make the HashMap here.
        private HashMap<books , books> stock;   
        public library ()
            book = new ArrayList<books>();
            member = new ArrayList<members>();
            stock = new HashMap<books, books>();       
        // to add a book to the catalogue, for example when its newly published (the book information)
        public void newBook(books bk)
            book.add(bk);
        public void TheStateOfTheLibrary()
            //print the library name and address
            System.out.println("BlueJ Library: 10 College Lane, AL10 9BL");
            // print list of the books (title, author, ISBN)
            System.out.println("Catalogue :");
            for (books bk : book){
                System.out.println(bk);
            System.out.println("");
             * print stock list to show all stocks in the library
             *it should show:
             *stock number, books name, by : thuthor. ISBN
            System.out.println("Stock List:");
            System.out.println("");
            System.out.println("Membership List:");       
            for (members memb : member){
                System.out.println(memb);
        public void addMember(members memb)
            member.add(memb);
        // to add a copy of a book to it's stock, when the library receives this item.
        public void addBookToStock(books sn)
           // i coudnt make it
    }thank you

    actually im new in java and i dont really understand the HashMap.A HashMap is like an array except the index values of the array aren't integers. If you declare an array like this:
    int[] nums = new int[10];
    the index values of the array are the integers 0-9. To store something in the array, you do something like this:
    nums[0] = 3;
    0 is the index value and at that index position in the array is the integer 3.
    With a HashMap, you can use index values other than integers for your array. For instance, you can use Strings:
    index value           value stored at that index position in the array
    "John"                           "232-0416"
    "Sally"                          "451-0091"To add an index value to the map and store a value at that index position, you would do this:
    myMap.put("Jane", "456-7654");
    To get the telephone number at index position "John", you would do this:
    myMap.get("John");
    However, you have to do a little more work on the object returned by get(). When you add objects, like String objects, to one of java's collections, they are automatically converted to type Object first and then added to the collection. Then, when you retrieve objects from a collection, they are returned as type Object, so you need to cast them to their original type:
    String result = (String) myMap.get("John");
    That statement gets you whatever is stored at index position "John" in the array, which happens to be the String "232-0416". You don't have to make that cast in java 1.5 when you use generics, which is what you are doing.
    One last point: in HashMap lingo, the index values in the array are called "keys".
    i have an error " cannot find symbol- method put(int,books)You defined your HashMap like this:
    private HashMap<books , books> stock;
    That tells java that you are going to be using 'books' objects for the index values of the array, and that the values stored at those index positions will be 'books' objects. But here:
    public void addBookToStock(Books sn, Books b)
            int key = sn.getStockNumber();
            stock.put(key,  b);       // the error is in this line.
    }you are trying to use an int as the index value of the array. Since you told java you would be using "books" as index values, it produces an error.
    You should also rename your Books class to "Book". A Book object does not consist of several books--it represents only one book. If you had a collection containing a bunch of Book objects, then it would make sense to name the collection "Books".

  • Problem in updating values in hashmap

    I have a hashmap(key,value), where key is a String and value is an ArrayList. It has following values:
    {500, [GRES]}
    {600, [GRES]}
    Now i check for the key 500 in the hashmap and want to update the value ArrayList for it with [GRES,TOEC].
    For doing this i have written code as follows:
    if(hashmap.containsKey("500")) {
        ArrayList hashDoc = (ArrayList) hashmap.get(500);
        hashDoc.add("TOEC");
        hashmap.put(500,hashDoc);
    }The problem i am facing with this code is that the value for key 600 is also changing to [GRES,TOEC], which i don't want.
    I just want to update the value for key 500.
    What should i do?

    Though there does not seem any problem with your code, I tried to simulate the same.
      public class HashMapDemo {
         public static void main(String[] args) {
              ArrayList l1 = new ArrayList();
              l1.add("1");
              ArrayList l2 = new ArrayList();
              l2.add("2");
              HashMap x = new HashMap();
              x.put("500", l1);
              x.put("600", l2);
              if(x.containsKey("500")) {
                   ArrayList tem = (ArrayList)x.get("500");
                   tem.add("1.2");     
                   //x.put("500", tem);
              System.out.println(l1);
              System.out.println(l2);
    }OutPut:
    [1, 1.2]
    [2]

  • Axis2: problems marshalling hashmap

    hi everybody!
    I'm having this problem using axis2 1.2: i want to send to a service a very simle hashmap like this:
    HashMap hash = new HashMap();
    hash.put("key", "text");
    And this is my client code where the hashMap is used:
    public static void main(String[] args1) throws AxisFault {
         try {
    RPCServiceClient serviceClient = new RPCServiceClient();
    Options options = serviceClient.getOptions();
    EndpointReference targetEPR
    = new EndpointReference(
    "http://localhost:8080/axis2/services/HashMapService");
    options.setTo(targetEPR);
    QName op = new QName("http://service.sample/xsd", "getKey");
    HashMap hash = new HashMap();
    hash.put("key", "text");
    Object[] opArgs = new Object[] { hash };
    Class[] returnTypes = new Class[] { String.class };
    Object[] response = serviceClient.invokeBlocking(op,
    opArgs, returnTypes);
    myResponse = (String)response[0];
    System.out.println(myResponse);
    catch(Exception e){
         System.out.println("exception: " + e.getMessage());
    The service has to send to the client the unique key of the hashMap. but, the response I receive is null. The problem is that the HashMap is not marshalled properly. This is the request Soap message:
    <?xml version='1.0' encoding='utf-8'?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
    <getKey xmlns="http://service.sample/xsd">
    <arg0 xmlns="">
    <empty>false</empty>
    <empty>false</empty>
    </arg0>
    </getKey>
    </soapenv:Body>
    </soapenv:Envelope>
    <arg0> element is the hashMap!!
    Can somebody help me, please? How can I marshall a HashMap?
    Thanks!!

    I am also facing the same problem , while sending hashmap to WS using axis2.
    Please suggest.

  • Having Problems with Hashmap

    Hi, I'm currently creating a sparsematrix for my assignment using a hash map however i've come across a problem with how i can set an element and returning using key objects
    My setElement method is
    public void setElement(int nrow, int ncol, float value) throws
    MatrixException {
    data.put(new SparseNode(nrow,ncol), value);
    and my get element is
    public float getElement(int row, int col) throws MatrixException {
    SparseNode node = new SparseNode(row, col);
              if (!data.containsKey(node)) {
              return 0;
    return (Float) data.get(node);
    where data is the map and node would be the key. The problem comes when i set the value where i give a key and this is set into the hashmap. unfortunatly the key is lost when the method exits so using the getElement method by creating a sparsenode with same characteristics as the original key won't work simply because it's not the original key. Is there another way to get around this? or some way to store the key.

    ok well i changed to to not include the SparseNode. Now it works but very very slow. I also noticed another post with a user with the same problem but it didn't really explain how to fix it properly. Any suggestions to make this code faster?
    import java.io.*;
    import java.util.*;
    public class SparseMatrix implements Matrix{
        private HashMap data; // non zero elements
         private int rows;
         private int columns;
        public SparseMatrix(int row, int columns) {
            data = new HashMap(row*columns);
            this.rows=row;
            this.columns=columns;
        public float getElement(int row, int col) throws MatrixException {
                if (row < 0 || col < 0 || row > this.getNumRows() || col > this.getNumCols()) {
                throw new MatrixException("Row or Column Number Beyond Dimension");
                     if (!data.containsKey((row*this.getNumCols()+col))) {
                        return 0;
            return (Float) data.get((row*this.getNumCols()+col));
        public void setElement(int nrow, int ncol, float value) throws MatrixException {
    //        if (row > this.row || col > this.col) {
    //           throw new MatrixException("Matrix index out of range");
            data.put((nrow*this.getNumCols()+ncol), new Float(value));
        public boolean isZero() {
            return data.isEmpty();
        // return the total number of rows in the matrix
       public int getNumRows(){
            return rows;
       // return the total number of rows in the matrix
       public int getNumCols(){
            return this.columns;
       // transpose matrix and return result as new matrix
        public Matrix transpose() {
            SparseMatrix a = new SparseMatrix(this.getNumCols(), this.getNumRows());
            for (int i =1 ; i<=this.getNumRows();i++) {
                for (int j = 1;j<=this.getNumCols();j++){
                      float value = getElement(i,j);
                     a.setElement(j, i, value );
            return a;
        * Subtracts a matrix to the current matrix and returns result as new matrix
        * @param a The Matrix to be subtracted
        * @return Returns the new matrix
       public Matrix subtract(Matrix a) throws MatrixException{
                 if (this.getNumRows() != a.getNumRows() || this.getNumCols() != a.getNumCols())
                    throw new MatrixException("Subtraction Cannot be Done due to Matrix Dimension MisMatch");
                if (a.isZero())
                    return this;
                    SparseMatrix ResultMatrix = new SparseMatrix(this.getNumRows(), this.getNumCols());
            for (int i = 1; i <= rows; i++) {
                for (int j = 1; j <= columns; j++) {          
                     float value = a.getElement(i,j);
                     float result = this.getElement(i,j) - value;
                     if (result < 0 || result > 0) {
                         ResultMatrix.setElement(i,j,result);
                 return ResultMatrix;
        // add matrix and return result as new matrix
        public Matrix add(Matrix a) throws MatrixException {
                if (this.getNumRows()!= a.getNumRows() || this.getNumCols()!= a.getNumCols())
                throw new MatrixException("Addition Cannot be Done due to Matrix Dimension MisMatch");
            if (this.isZero())
                return a;
            if (a.isZero())
                return this;
                SparseMatrix ResultMatrix = new SparseMatrix(this.getNumRows(), this.getNumCols());
            for (int i = 1; i <= rows; i++) {
                for (int j = 1; j <= columns; j++) {          
                     float value = a.getElement(i,j);
                     float result = this.getElement(i,j) + value;
                     if (result < 0 || result > 0) {
                         ResultMatrix.setElement(i,j,result);
                 return ResultMatrix;
    // multiply matrix and return result as new matrix
         public Matrix multiply(Matrix a) throws MatrixException {
                              if (this.getNumCols() != a.getNumRows())
                throw new MatrixException("Multiplication Cannot be Done due to Matrix Dimension MisMatch");
            if (this.isZero() || a.isZero())
                SparseMatrix Temp = new SparseMatrix(this.getNumRows(), a.getNumCols());
                return Temp;
             SparseMatrix ResultMatrix = new SparseMatrix(this.getNumRows(), this.getNumCols());
              for(int i=1;i<=this.getNumRows();i++)
                   for(int j=1;j<=a.getNumCols();j++)
                                  float Result =0;
                                  for(int k=1;k<a.getNumCols();k++)
                                       Result = Result + this.getElement(i,k)*a.getElement(k,j);
                                  ResultMatrix.setElement(i,j,Result);
              return ResultMatrix;
         // print matrix in the format:
       // a11 a12 ... a1m
       // an1 an2 ... anm
        public void print(PrintStream out) {
             //System.out.println(data.toString() +"\n=====================");
            for (int i = 1; i <= this.getNumRows(); i++) {
                for (int j = 1; j <= this.getNumCols(); j++) {
                    float aData = this.getElement(i, j);
                    out.print(" " + aData + "");
                out.println();
    }

  • HashMap , int [][] - key , compareTo override problem , help

    i've a hashmap Map<int [][] , Integer> and i want to get the corresponding value for int a[][] from the map.
    if i use , map.containsKey(a)
    it doesn't compare as required( it doesn't consider order )
    so i thought of using class key implementing comparable like this,
    class key implements Comparable
              int a[][];
              public key(int p[][])
              {     a=p;     }
              public int compareTo(Object o)
                            key k = (key)o;
                   for(int i = 0 ; i < 3 ; i++)
                        for(int j = 0 ;j < 3 ; j++)
                             if(a[i][j]!=k.a[i][j])     return 1;
                   return 0;
    }now when i create a key ,
    key KK = new key(a) // a is int[][]
    map.containsKey(KK) doesn't invoke compareTo method itself ..
    don't what the problem is.
    but when i try . TreeMap it invokes compareTo method
    but don't know why , it acts as before when Map<int [][] , Integer> was used.. any idea
    Thanx

    manishmulani@nitk wrote:
    wil the following way of overriding hashcode work??
    class key
              int a[][];
              public key(int p[][])
              {     a=p;     }
              public boolean equals(Object o)
                   key k = (key)o;
                   for(int i = 0 ; i < 3 ; i++)
                        for(int j = 0 ; j < 3 ; j++)
                             if(a[i][j]!=k.a[i][j])     return false;
                   return true;
              public int hashCode()
                   return a.hashCode();
    NO! When doing that, you will get undesirable results. Execute the following lines of code and examine the output:
    System.out.println(new int[][]{{1,2},{3,4}}.hashCode());
    System.out.println(new int[][]{{1,2},{3,4}}.hashCode());This is better:
    public int hashCode() {
      int hash = 1, mutliplier = 1;
      for(int[] row: array) {
        for(int val: row) {
          hash ^= (val * mutliplier);
          mutliplier *= 10;
      return hash;
    }(Untested!!!)
    ok this will be same if i use TreeMap and implement Comparable<key> and override compareTo() right??Err, yes, more or less. Of course, a HashMap and TreeMap are not the same.

  • Hashmap and array list problems

    This is an assignment I have to do and I do NOT expect anyone to do the coding for me. I am just looking for some direction as I have no clue where to go from here. Any guidance would be very welcomed.
    We were given code that used just an Array lisThis is an assignment I have to do and I do NOT expect anyone to do the coding for me. I am just looking for some direction as I have no clue where to go next. Any guidance would be very welcomed.
    We were given code and told to "Modify the MailServer so that it uses a HashMap to store MailItems. The keys to the HashMap should be the names of the recipients, and each value should be an ArrayList containing all the MailItems stored for that recipient. " Originally it was just an ArrayList named messages. There is also a MailClient and MailItem class.
    I think I can post the messages using the HashMap now, but can't test it. I get a compiler error saying else without if even though I have an if statement. Even if I can compile, I need to make sure I am on the right track with the getNextMailItem method. It is the one I am stuck on and if I can get it to work, I can probably modify the other methods.
    I would really appreciate feedback on that one method.
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    public class MailServer
         // Storage for the arbitrary number of messages to be stored
         // on the server.
         private HashMap messages;
         private ArrayList list;
         private MailItem item;
          * Construct a mail server.
         public MailServer()
             messages = new HashMap();
             list = new ArrayList();
          * Return the next message for who. Return null if there
          * are none.
          * @param who The user requesting their next message.
         public MailItem getNextMailItem(String who)
              Iterator it = list.iterator();
              while(it.hasNext())
                MailItem item = (MailItem)it.next();
                if(messages.containsKey(who));
                    return item;
               else
                   return null;
          * Add the given message to the message list.
          * @param item The mail item to be stored on the server.
         public void post(String name, MailItem item)
             if(messages.containsKey(name))
                    list = (ArrayList) messages.get(name);
                    else {
                        list = new ArrayList();
                        list.add(item);
                        messages.put(name, list);
    }[                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    The way I understand this is that MailItems are stored in per user ArrayLists, and that the ArrayLists are stored in the HashMap, and use the username as a key,
    HashMap messages = new HashMap();
    //ArrayList userMailItems = new ArrayList(); this should not be declared here, only the messages mapso given a User name, you need to get the list of mail items for that user out of the hashMap, and then return the next MailItem from the list. So given that, you don't even need to Iterate over the list:
    public MailItem getNextMailItem(String who)
    ArrayList list = (ArrayList)messages.get(who);
    if(list == null || list.size() == 0)
    return null;
    //now we get the next item from the list, we can call remove, since it returns the object we are removing.
    MailItem item = (MailItem)list.remove(0);
    return item;
    }

Maybe you are looking for