Hashmap Question

I have this method that needs to return a String of possible exits of a room, by reading it from the HashMap.
    public String getExitstring()
        String returnString = "Exits:";
        Set <String> keys = exits.keySet();
        for(String exit : keys)
            returnString += " " + exit;
        return returnString;
    }However, it gives me the error "cannot find symbol - class Set". I'm lost here, since it's a method according to the JavaDoc. And yes, I import java.util.HashMap.

Grawl wrote:
However, it gives me the error "cannot find symbol - class Set". I'm lost here, since it's a method according to the JavaDoc. And yes, I import java.util.HashMap.Why would you think that importing HashMap would also import Set? They're not the same class. To use Set you need to import java.util.Set
And what do you mean that Set is a 'method' according to the JavaDoc? A Class is not the same thing as a method.

Similar Messages

  • HashMap question please

    Dear All,
    i am using in my code a hashmap< ArrayList<Byte>,String>
    and :
    Long bits = new Long(0);
    for (int i = 0; i < nodes.length; i++) {
    if (nodes.getValue() != null) {
    ArrayList<Byte> search = nodes[i].getValue();
    String s = huffmanTable.get(((ArrayList<Byte>)search));
    System.out.println(huffmanTable.values());
    System.out.println(huffmanTable.keySet());
    System.out.println("String" + s);
    System.out.println(" nodes.get(i).getValue() "+ nodes[i].getValue());
    System.out.println(huffmanTable);
    bits += (nodes[i].getFrequency() * s.length());
    These two lines :
    System.out.println(huffmanTable.values());
    System.out.println(huffmanTable.keySet());
    resulted in :
    [1100, 000, 100, 010, 1011, 011, 1010, 001, 111, 1101]
    [[3, 72], [3, 68, 32], [3, 87, 72], [2, 79, 85], [1, 32, 72], [1, 87, 82], [2, 72, 32], [1, 71, 79], [1, 65, 84], [1, 71, 84]]
    although the s was null and gave me null pointer exceptin !! which is soo wiered , i can't get why ?? or how although it contains all values + when i printed : nodes[i].getValue();
    it was = [3, 72] !!
    can any body help me as i really want to know how come the HashMap can't feel the ArrayList , even the method .contains of the HashMap gave me false !!!!
    wishing to find any help guys
    thank you in Advance.
    Regards,
    D.Roth.

    Hope the code snippet below might be of some help....
    HashMap<String,ArrayList<String>> hm = new HashMap<String,ArrayList<String>> ();
    ArrayList<String> al = new ArrayList<String>();
    al.add("java");
    al.add("solaris");
    al.add("sun");
    al.add("SDN");
    hm.put("ArrayList",al);REGARDS,
    RaHuL

  • TreeMap or HashMap question

    Hi,
    I noticed that if I use the put method with the string as the parameter for any objectB, I would get that objectB back by using the get function with that string. However, if I use the put method as an objectA as a parameter for any objectB, I would not get back objectB even if objectA all the fields exactly the same. Is there a way to somehow override the checking mechanism like a comparator? Thanks.

    To use a custom object as a key, you must override the following methods in Object
    equals()
    hashcode()

  • How to write Question paper program in jsp....

    Hi..,
    This is sure from india. I would like to develop online examination project. Everything is ok. But i have a problem at deveop of question paper. I have 10 questions in my database. I would like display those questions one by one. How can i done this job. Please any one guide me. Because, i am new to this concept.
    with regards
    sure..)-

    First you need to extract all the question from database..
    Then put all of those questions in any of collection object...
    Then set this collection object in request as attribute..
    Keep this object in request till all question are not shown(you can eliminate questions after the have been asked)..
    Code might be like this.
    HashMap result = new HashMap();
    connection = .......;
    Statement stmt=connection.createStatement();
    rs = stmt.executeQuery("Your query");
    int count=0;
    while(rs.next())
    count++;
    String question = rs.getString("colName");
    result.put(""+count,question); //( ""+count)>>>>>means converting int to String
    request.setAttribute("questions",result);
    ====================================================
    now in every JSP which is intended to display a question will have to get this result object..
    Lets assume we are about to display first question()....
    ===========================================
    //////// First get result map from request
    HashMap questions = (HashMap)request.getAttribute("questions");
    String count;
    count = request.getAttribute("count");
    if(count==null)
    count="1";
    String question = questions.get(count);
    count = new String(""+(Integer.parseInt(count).intValue()+1));
    ///Now do what you have to do with this questionresult
    questions.remove();
    request.setAttribute("count",count);////setting question no in request
    request.setAttribute("questions",questions);////setting rest of questions in request
    ===================================================
    hope this might be helpful........
    if there is any problem you can consult me anytime

  • Doubt on hashmap

    Map qmap = new TreeMap( //some initialized Map);
    Iterator faqs = qmap.values().iterator();
    int count=1;
    Map params = new HashMap();
    while(faqs.hasNext()) {
    params.put("question" , faqs.next());
    params.put("qid" , topic + "_" + count);
    count++;
    my question is that , will this code not be wrong as the key values will not be unique in the HashMap (params)......

    That's right. After the loop you'll only have two
    keys in the HashMap: "question" and "qid".So if question and qid are related you could design a class with these two as parameters. Than you store objects of that class in an ArrayList instead.
    Or you could associate qid with question in a HashMap like
    while(faqs.hasNext()) {
       params.put(topic + "_" + count , faqs.next());
       count++;
    }That would give you unique keys. You have many options depending on what you want to accomplish.

  • Question | Using JSTL to Display elements of an ArrayList of HashMaps

    Hi All,
    I would like some advice on the following code snippet which is a representation of my real code. Please see below for the code snippet and the specific questions I have.
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <%
    // This Object is an ArrayList of HashMaps
    MyClassDataBean myDb =  (MyClassDataBean)session.getAttribute("testDataBean");
    // Adding myDb to the pageContext so that EL can be used to render components in this Object
    pageContext.setAttribute("myDb",myDb);
    pageContext.setAttribute("column1",MyConstants.COLUMN1);
    pageContext.setAttribute("column2",MyConstants.COLUMN2);
    %>
    <html>
    <head></head>
    <body>
         <c:choose>
          <c:when test="${myDb != null}" >
             <c:forEach var="hashMapAsRow" items="${myDb}" varStatus="lineInfo">
              <tr>
                  <td><c:out value="${hashMapAsRow[column1]}" /></td>
               <td><c:out value="${hashMapAsRow[column2]}" /></td>
               </tr>
         </c:forEach>
         </c:when>
         <c:otherwise>
         <tr><td colspan="100%">No Data Exists</td></tr>
         </c:otherwise>
       </c:choose>
    </body>
    </html>Question: Is there an alternative to accessing elements using the core tag library in this Object without using pageContext.setAttribute() ? If not, would the c_rt library be better to use in this scenario? If so, could someone give me an example of the right way to use it based on the above example?
    Thanks,
    Joe

    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <c:set var="myDb"  value="${sessionScope.testDataBean}" />
    <html>
    <head></head>
    <body>
          <c:choose>
           <c:when test="${myDb != null}" >
              <c:forEach var="hashMapAsRow" items="${myDb}" varStatus="lineInfo">
               <tr>
                   <td><c:out value="${hashMapAsRow['column1']}" /></td>
                 <td><c:out value="${hashMapAsRow['column2']}" /></td>
                </tr>
         </c:forEach>
          </c:when>
          <c:otherwise>
         <tr><td colspan="100%">No Data Exists</td></tr>
          </c:otherwise>
        </c:choose>
    </body>
    </html> or the one below
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <html>
    <head></head>
    <body>
          <c:choose>
           <c:when test="${sessionScope.testDataBean != null}" >
              <c:forEach var="hashMapAsRow" items="${sessionScope.testDataBean}" varStatus="lineInfo">
               <tr>
                   <td><c:out value="${hashMapAsRow['column1']}" /></td>
                 <td><c:out value="${hashMapAsRow['column2']}" /></td>
                </tr>
         </c:forEach>
          </c:when>
          <c:otherwise>
         <tr><td colspan="100%">No Data Exists</td></tr>
          </c:otherwise>
        </c:choose>
    </body>
    </html> is this the one which you are looking for ??
    REGARDS,
    RaHuL

  • Question about efficiency, should i use hashmap?

    Hi all
    i read a csv file and store each line's data into a class MyData.
    this class contains a variable of id - unique for object.
    i want to store all my MyData object in a collection for later use.
    if i want to access them in the fastest way, should i store my objects in a hashmap, and the key value would be their id?
    like -
    HashMap hashmap = new HashMap();
    MyClass mc1 = new MyClass(1); //id =1
    MyClass mc2 = new MyClass(4); //id =4
    //i add the objects
    hashmap.put(mc1.getID(),mc1);
    hashmap,put(mc2.getID(),mc2);
    //then when i want to get a certain object, where id is 4:
    MyClass mc = hashmap.get(4);should i use other collection? or is it fine that way?
    Thanks!

    jwenting wrote:
    don't worry about microoptimisations like selecting a collection class based on how fast it is unless and until you have written evidence that the class you had initially chosen was the sole reason for unacceptably poor performance (which will hardly ever matter, the only time I've ever encountered that was with an ancient web application making extensive use of Vector, where switching to ArrayList made it an order of magnitude faster).Hmmm... I do diagree with that statement, but then again I'm an old f@rt... I cut my teeth on the gory gizzards of all manor of data-structures, and I still believe that selection of the "correct" data structure(s) is a core implementation issue... especially where efficiency is (even occasionally) desirable.
    I haven't seen the same big gains when replacing Vector with ArrayList... in fact, I've only seen a very marginal (<10%) increase in "overall" throughput... I have seen a couple of orders of magnitude (or thereabouts) increase when I swapped a Vector<Integer> for an int[], but that was in the inner-loop of an inherently n^2 (I think) spatial algorithm.... and I also made it reuse the int[], instead of creating, growing and throwing away the vector every time through the outer loop. Malloc is expensive ;-)
    I'd be interested to hear more details about under the conditions under which ArrayList is 10 times faster than Vector, because I do a lot of work on a 1.3/1.4 era codebase, which is full of Vectors and HashTables... and I would like to be able to make a case for an en mass replacement (and generifying) of the "old school" datastructures... but alas, I see very little bang for our buck, so I just bite my toungue and continue using Vectors, even in new code, because so many existing "helpers" take a (explicitly) Vector parameter.
    I heard a "rumor" somewhere (probably a thread here) that there's talk of discontinueing support for non-generic collections in 1.7, because they (the API/VM developers) are having to (sort of) maintain two divergent versions of every collection related thing... and nothing annoys a developer more than that, right... so Please can anyone confirm or repudiate this "rumour".
    Cheers. Keith.

  • HashMap.clone() question?

    Dear all,
    I got something really confused me. Here is a programme from JDT
    http://developer.java.sun.com/developer/JDCTechTips/2001/tt0306.html#cloning
    import java.util.*;
    class A implements Cloneable {
    public HashMap map;
    public A() {
    map = new HashMap();
    map.put("key1", "value1");
    map.put("key2", "value2");
    public Object clone() {
    try {
    A aobj = (A)super.clone();
    aobj.map = (HashMap)map.clone();
    return aobj;
    catch (CloneNotSupportedException e) {
    throw new InternalError(e.toString());
    public class CloneDemo5 {
    public static void main(String args[]) {
    A obj1 = new A();
    A obj2 = (A)obj1.clone();
    obj1.map.remove("key1");
    System.out.println(obj2.map.get("key1"));
    The output is :
    Value1
    From my viewpoint, the keys and values in the obj1 have been cloned to obj2, because even the key1 of obj1 is deleted, the key1 of obj2 is still there.
    However, according to the API specification, in the Hashmap.clone(), "The keys and values themselves are not cloned."
    Please clarify this for me. Thank you.
    Leo
         

    The keys and values are object references, and when you clone a HashMap you get a new HashMap with copies of those references - the referenced objects are not cloned. When you remove something from the first hashmap, the second hashmap still contains a reference to the object you just removed, so it still contains it. To see the difference, try putting a mutable object into the HashMap before cloning it. Then get the object from either of the HashMaps, alter the state of that object, get value held against the same key in the other HashMap, and print its state - you will see that the change has been reflected in both HashMaps because both HashMaps are referencing the same object. Try this:
    import java.util.*;
    class A implements Cloneable {
         public HashMap map;
         public A() {
              map = new HashMap();
              map.put("key1", new B("value1"));
              map.put("key2", new B("value2"));
         public Object clone() {
              try {
                   A aobj = (A) super.clone();
                   aobj.map = (HashMap) map.clone();
                   return aobj;
              } catch (CloneNotSupportedException e) {
                   throw new InternalError(e.toString());
    class B {
         String s;
         B(String s) {
              this.s = s;
         public String toString() {
              return s;
    public class CloneDemo5 {
         public static void main(String args[]) {
              A obj1 = new A();
              A obj2 = (A) obj1.clone();
              B b1 = (B)obj1.map.get("key1");
              B b2 = (B)obj2.map.get("key1");
              System.out.println(b1);
              System.out.println(b2);
              b1.s = "A changed value";
              System.out.println(b1);
              System.out.println(b2);
    }

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

  • How to store data in hashmap so that it can be used by different methods.

    Hello,
    I have an ADF/JSF application and the database is DRM. The program gets data from DRM into this hashmap. Program needs this data frequently. Getting this HashMap is very resource intensive due to a lot of data it has.
    I want to get the data in HashMap once ( I can do this - no problem).  But where/how do I keep it so that different methods can just use this and not make individual trips to DRM? It may be a very basic java question but I seem to be stuck :)
    I am not very concerned about the HashMap part, it can be any collection - the question is of storing it so that it can be used over and over.
    Thanks,

    User,
    If I understand you correctly, you have a JSF application that needs to store data in a HashMap such that it can be accessed over and over? You could put the hashmap into an appropriately-scoped managed bean and access it from there. I'm not sure what a "DRM" is (a digital rights management database, perhaps, in which case it's a "database"), so there is something special about a "DRM" that we need to know, please share.
    John

  • How to get selected row data of an ADF table in HashMap?

    Hi,
    Can anyone please tell me how to selected row data of an ADF table in HashMap like :
    Object obj = pageTable.getSelectedRowData();
    JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)obj;
    Now in above code I want the convert rowData in HashMap.
    Can anyone please tell me how to do that? Its urgent.
    Thanks,
    Vik

    Vik,
    No need to ask the same question 3 times...
    In [url http://forums.oracle.com/forums/message.jspa?messageID=4590586]this post, Nick showed you how to get the Row.
    If it were so urgent, you could have done a little reading of the javadocs to come up with code like this (not tested, up to you to do that)
    HashMap m = new HashMap();
    Row r = get it like Nick showed you to;
    Object values[]=r.getAttributeValues();
    String names[]=r.getAttributeNames();
    for (int i=0; i<r.getAttributeCount(); i++)
    m.put(names, values[i]);

  • A question about concurrency and static getter methods

    Hello
    I have a class with some static methods. they just return a reference and doesnt apply any changes.
    something like this:
    public class FieldMapper {
            private static Map<Class,Map<String,String>> fieldMap = new HashMap<Class,Map<String,String>>();
            public static getFields(Class clazz){
                  return fieldMap.get(clazz);
    }my question is, let's consider many users connect to my server and each has its own session, now assume one user want to use FieldMapper.getFields(User.class) and another is going to call FieldMapper.getFields(Employee.class) at same time or a bit milli seconds after, and this method is not synchronized, is there any conflict in calling the method? would this method return wrong reference to the first invocation?
    in genereal, may the concurrency make problem on reading resources? or just on changing resources?
    Thank you very much in advance.

    To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by:
    Initializing an object reference from a static initializer;
    Storing a reference to it into a volatile field or AtomicReference;
    Storing a reference to it into a final field of a properly constructed object; or
    Storing a reference to it into a field that is properly guarded by a lock. The internal synchronization in thread-safe collections means that placing an object in a thread-safe collection, such as a Vector or synchronizedList, fulfills the last of these requirements. If thread A places object X in a thread-safe collection and thread B subsequently retrieves it, B is guaranteed to see the state of X as A left it, even though the application code that hands X off in this manner has no explicit synchronization.
    Now in the case you have specified you are using HashMap. Which is not designed to be threadsafe as opposed to HashTable or concurrentHashMap. In such a case I would advise against using this. The concurrency problem is caused by race conditions on mutable objects, whether it is reading or writing. If it is mutable, it is susceptible to race conditions. IMHO
    &spades;

  • Iterating performance: ArrayList, LinkedList, and Hashmap for N 1,000,000

    I have seen some websites discussing about the performance of ArrayLists, LinkedLists, and Hashmaps:
    http://forum.java.sun.com/thread.jspa?threadID=442985
    http://java.sun.com/developer/JDCTechTips/2002/tt0910.html
    http://www.javaspecialists.co.za/archive/Issue111.html
    http://joust.kano.net/weblog/archives/000066.html
    If I understand it right an ArrayList in general is faster for accessing a particular element in the collection and I can't find some pro's of using a LinkedList.
    My question is: If I only use a large collection with more than 1 million elements for iterating from begin to end (i.e. for loop), is it faster to use a linked list or a custom linked list instead of an arraylist (or hashmap)? Since you can iterate "directly" through a (custom) linked list, which is not possible with a arraylist?
    Edited by: 9squared on Nov 23, 2007 1:48 PM

    Thanks for the help, I wrote some code and tested it
    import java.util.ArrayList;
    import java.util.List;
    import java.util.LinkedList;
    public class TestTemp {
         public static void main(String[] args) {
              List<Node> a = new ArrayList<Node>();
              Node b = new Node("a");
              String[] c = new String[10000000];
              Node temp = b;
              for (int i = 0; i < 10000000; i++)
                   a.add(new Node("a"));
                   temp.next = new Node("b");
                   temp = temp.next;     
                   c[i] = "c";
              long tstart;
              tstart = System.currentTimeMillis();
              for (int i = 0; i < 10000000; i++)
                   c[i] = "cc";
                   if (i%200000 == 0)
                        System.out.println("Array " + i + ": " + (System.currentTimeMillis()-tstart));
              tstart = System.currentTimeMillis();
              temp = b;
              for (int i = 0; i < 10000000; i++)
                   temp.next.text = "bb";
                   temp = temp.next;
                   if (i%200000 == 0)
                        System.out.println("LinkedList " + i + ": " + (System.currentTimeMillis()-tstart));
              tstart = System.currentTimeMillis();
              for (int i = 0; i < 10000000; i++)
                   a.get(i).text = "aa";
                   if (i%200000 == 0)
                        System.out.println("ArrayList " + i + ": " + (System.currentTimeMillis()-tstart));
    public class Node {
         public String text;
         public Node next;
         public Node(String text)
              this.text = text;
    }Here are some results in milliseconds, and indeed just iterating doesn't take very long
    Elements     Linked     Arraylist     Array
    200000     0     0     1
    400000     5     13     5
    600000     9     22     9
    800000     14     32     12
    1000000     20     42     16
    1200000     25     52     19
    1400000     31     63     23
    1600000     37     72     26
    1800000     42     82     30
    2000000     47     92     33
    2200000     51     101     37
    2400000     56     112     40
    2600000     60     123     44
    2800000     65     134     47
    3000000     69     143     51
    3200000     73     152     55
    3400000     78     162     59
    3600000     84     175     63
    3800000     103     185     67
    4000000     108     195     70
    4200000     113     207     74
    4400000     117     216     78
    4600000     122     225     81
    4800000     127     237     85
    5000000     131     247     88
    5200000     136     256     92
    5400000     142     266     97
    5600000     147     275     101
    5800000     153     286     107
    6000000     159     298     113
    6200000     162     307     117
    6400000     167     317     121
    6600000     171     326     125
    6800000     175     335     128
    7000000     180     346     132
    7200000     184     358     136
    7400000     188     368     139
    7600000     193     377     143
    7800000     197     388     147
    8000000     201     397     150
    8200000     207     410     154
    8400000     212     423     157
    8600000     217     432     162
    8800000     222     442     167
    9000000     227     452     171
    9200000     231     462     175
    9400000     236     473     178
    9600000     242     483     182
    9800000     249     495     185
    10000000     257     505     189

  • Need help with locating a key using a value in a HashMap.

    I am quite new to Java and programming, and am just learning this in High School (enjoying it thoroughly). Sorry if I don't respect the etiquette or formatting of this board (it's unintentional).
    I am using the book, Objects First Wth Java A Practical Introduction Using Blue J and am working on extensively improving the "World of Zuul" project. Which is a text-based adventure game.
    Here is a code sample;
    public String getNameFromList(String name)
      boolean found = false;
      Set pairSet = xItemList.entrySet();
      for(Iterator iter = pairSet.iterator(); (found == false && iter.hasNext());){
      Item currentItem = (Item) iter.next().getValue();
      String currentKey = currentItem.getName();
      if(name.equals(currentKey)){
        String changedName = iter.next().getKey();
        return changedName;
    error; cannot resolve symbol:
    method: getValue()xItemList is a HashMap with String keys, and Item values.
    The relevant field of Item is name, which is a string.
    The currentKey local variable is a little misleading, it is the current name, but acts as the 'key' when looking for the actual key.
    changedName (if the parameter name is found from the item.getNames()), is what the method returns, the key associated with a object (by looking at the object's field).
    My objective for this method is for it to have a name as a parameter, which it searches for in the HashMap (by Iteration over the entrySet - or I suppose iteration over Set values(), but this loses which object value is tied to which key, doesn't it?), and returns the respective key.
    Any help would be very much appreciated (even if it is telling me that this can't be done with HashMaps!).

    It's not clear to me what your question is, or if indeed you even have a question.
    You seem to be having a problem with types. Iterators return Objects.
    So in this line:
      Item currentItem = (Item) iter.next().getValue();The iterator's next() method is returning an Object, and you're trying to call getValue() on that Object. But Object doesn't have a getValue() method. That would explain your error message. Map.Entry does; you apparently meant to call Map.Entry's getValue() method. You would cast the result of iter.next() to Map.Entry before you call getValue().
    Also you're calling next() on your iterator twice in the body of the loop, which means you're getting two different values... this is probably not what you intend.
    But you're making this more complicated than it needs to be anyway.
    Why are you iterating through the set of entries in the HashMap?
    The whole point of a Map is that you get an item using an object as the key. Just do xItemList.get(name). Right?

  • Stuck in HashMap + equals() behaviour

    I am studying the SCJP 6, and got stuck in one example from the book.
    package map583;
    import java.util.*;
    public class Dog {
        public Dog(String n) {
            name = n;
        public String name;
        public boolean equals(Object o) {
            if(o instanceof Dog){
                Dog dog = (Dog) o;
                if(dog.name.equalsIgnoreCase(this.name)){
                    return true;
                }else{
                    return false;
            } else {
                return false;
        public int hashCode() {
            return name.length();
    package map583;
    import java.util.*;
    public class MapTest {
        public static void main(String[] args) {
            Map<Object, Object> m = new HashMap<Object, Object>();
            Dog d1 = new Dog("clover");
            m.put(d1, "Dog key");
            d1.name = "123456";
            System.out.println(m.get(d1));
    }The output is "Dog Key", what I question is when changing d1.name to "123456", hashcode() returns same value, BUT equals() method compares to String values, obviously the Dog object name value in HashMap is "clover", but the d1.name value is "123456", and they are not the same.
    This gives me another assumption. Is the changing of name to "123456" actually changes the dog object name value in the HashMap? Because the dog object stored in the HashMap is d1. But when I changed the code to :
            d1.name = "1234567890";
            System.out.println(m.get(d1));It outputs null now. So it proves that the dog object stored in the HashMap CANNOT be changed by changing d1.name value, so how to explain my first question?

    roamer wrote:
    Now same question again, then how to explain this?
    d1.name = "1234567890";
    System.out.println(m.get(d1));   // returns "null". #2the key in the HashMap stores the variable name d1, which points to the Dog object modified by the above statement, which name is "1234567890" now. So when searching the HashMap, the argument passed (d1) is actually referencing the SAME object as the variable in the HashMap (which is also d1), same hashcode AND returns true in equals() method.
    So what the hell why this statment fails but #1 succeeded. When thinking in the same logic flow.Okay, you are REALLY missing the point here. We never get to the equals check because the hashCode is different, so it doesn't matter if it's the same object. This is what I tried to explain to you earlier: The messed up hash code might make you not even have a chanceto compare the object. With this very simple hashCode, changing the name to a different one of the same length didn't alter the hashCode, but changing it to a different length did, so we searched the wrong bucket, and therefore never had a chance to find the object.
    Dog d1 = new Dog("clover"); // A
    m.put(d1, "Dog key"); // B
    System.out.println(m.get(d1)); // C   // returns "Dog key". ---- Yes, it is normal.
    d1.name = "123456"; // D
    System.out.println(m.get(d1)); // E   // returns "Dog key". #1
    d1.name = "1234567890"; // F
    System.out.println(m.get(d1)); // G   // returns "null". #2A: Create an instance of Dog. name = "clover", stick a reference to it in variable d1
    B. Put a an entry in the map where the key is that Dog and the value is "Dog Key". The reference to the key is stored in the bucket for hashCode=6
    C. Search for d1 in the map. This means 1) Get hashCode of object pointed to by d1 (6). 2) Find that bucket. 3) For each element in that bucket, check if it equals(d1) 4. When we find the Dog in that bucket that equals(d1) because its name equals(d1.name), we return the corresponding value: "Dog key"
    D. Set the name of the only Dog object we've created to "123456". This does not change its bucket in the map, because hashCode() uses name.length(), which is still 6.
    E. Same as C, except now we're loooking for name of "123456" instead of "clover"
    F. Set the Dog object's name to "1234567890". This changes its hashcode, so it is (probably) no longer in the same bucket.
    G. Search for d1 in the map. This means 1) Get hashCode of object pointed to by d1 (10). 2) Find that bucket. 3) For each element in that bucket, check if it equals(d1) 4. Since it's a different bucket, it doesn't matter if equals() is true, or even if == is true. The object is not found because we searched the wrong bucket.
    Note also what would happen if we had two different Dog objects. If we change the one in the map from "clover" to "123456", we'll still search the same bucket, but we won't return anything because d1 is a different object and "clover".equals("123456") is false. The second case would still return null for the same reason it currently does--we'd never even get to search the right bucket.
    Edited by: jverd on Feb 2, 2010 7:34 PM

Maybe you are looking for

  • Date and time expired oracle user

    Dear Experts, as per my daily activities now i triggered backup through legato and it is given an below error 'CONNECT system/*******' ORA-28011: the account will expire soon; change your password now and i checked in database and found user system s

  • No Idocs arrived from the source system.

    Dear All, Please read this issue carefully. Error Message is that "No Idocs arrived from the source system." In the Details Tab: Trasnfer( IDOCS &TRFC):Missing Messages or warinings. Request IDOC:Application Documnet posted from BW side and it is gre

  • Safari/Firefox need to Cmd+Q twice to quit.

    No big deal, but it's bored. It has been a long time, everytime I quit the Safari or Firefox, few secs later, the icon on the dock jumps again - the browser starts again. And I need to Cmd+Q one more time to quit it. Someone told me to delete the .pl

  • Is there an additional Typekit charge for fonts with Creative Cloud membership?

    Is there an additional Typekit charge for fonts with Creative Cloud membership?  I am not clear if these are trial fonts or if there will be a charge for using them permanently in Adobe Illustrator CS6.  Thanks for any assistance.

  • OSI Layer Question

    Which layers of the osi model are host to host layers ? 1. Transport, session,Presentation, Application 2. Network, Transport, Session, Presentation 3. Datalink, Network, Transport, Session 4. Physical, Datalink,Network, Transport Which is the correc