In HashMap

In HashMap i got one compilation error that is hm.put(....) ,the showing errors at dot(.) we declared util package and java.lang package, but agian its shows same error why?

In HashMap i got one compilation error that is hm.put(....) ,the
showing errors at dot(.) we declared util package and java.lang
package, but agian its shows same error why?Can you show the relevant piece of source code that generates this
compilation diagnostic? Can you show us the diagnostic itself too?
BTW, there's no need to import the java.lang package.
kind regards,
Jos

Similar Messages

  • Using HashMap's ContainsKey() in JSTL

    Can we use HashMap's containsKey() in JSTL <c:if > statement
    I tried with the sample
    <html:select property="Type" multiple = "true" size = "3">
    <option value='<c:out value="${key}"/>'
    <c:if test="${requestScope.test.containsKey(key)}">
    selected
    </c:if>     
    <c:out value="${value}"/></option>
    </html:select >
    When i executed the above code i encountered JSP Error
    Can any one please let me know the correct code

    You can't call java methods from JSTL. It uses the EL - not java.
    However there is a solution.
    You access maps using the square brackets [ ] notation.
    ie ${test[key]}
    is the same as test.get(key)
    try
    <c:if test="${ not empty test[key] }"/>
    However seeing as you are using the struts tags, doesn't that automatically take care of this for you? Why don't you use the struts tags for the options list as well as the select? Just a thought :-)
    Cheers,
    evnafets

  • Returning a HashMap K, M from a method of a class typed M

    So, this is what I have. I have a class parameterized for a bean type of a collection it receives, and in a method of the class, I need (would like) to return a HashMap typed as <K, M> as in:
    public class MyClass<M> {
       private Collection<M> beanList;
       public HashMap<K, M> getMap(  /* what do I do here */ );
    }I tried to cheat from looking at the Collections.sort method, knowing it uses the List type in its return type as in:
    public static <T extends Comparable<? super T>> void sort(List<T> list)So, I am trying:
    public HashMap<K, M> getMap(Class<K> keyType)But, it is telling me I need to create class K.
    So... how does the Collections.sort method get away with it and I can't????
    I suppose I could write the method as:
    public HashMap<Object, M> getMap()but became somewhat challenged by my first guess.
    Any ideas... or just go with the HashMap with the untyped key?

    ejp wrote:
    provided K is inferable from the arguments.Or from the assignment context:
    Set<String> empty = Collections.emptySet();
    Otherwise you have to parameterise the class on <K, M>.You may also specifically provide K when you use the method if the context doesn't give the compiler enough information or if you want to override it.
    Example:
    Set<Object> singleton1 = Collections.singleton("Hello"); //error
    Set<Object> singleton2 = Collections.<Object>singleton("Hello"); //fineEdited by: endasil on 14-May-2010 4:13 PM

  • Nulls from HashMap.get(Object)

    I understand that I get the nulls because the Object is not in the map. But is there some elegant way to have it default to the empty String?
    Right now, after I grab all my data into variable with HashMap.get(Object), I go and check each once for null, and assign it the empty String instead. This is a lot of lines of code for something that is so basic.
    I know i could initialize them all to the empty string, and then for each variable, check the HashMap with containsKey(Object) before assigning with HashMap.get(Object). Now, would I be correct in assuming the compiler would optimize this for me and not actually check the HashMap twice for the same Object? And... even if that is the case, its still just as many lines of code.
    Is there perhaps some more elegant way?
    String exchange = parameterMap.get("exchange");
    String messageType = parameterMap.get("messagetype");
    String traderTimeStamp = parameterMap.get("traderTimeStamp");
    String exchangeTimeStamp = parameterMap.get("exchangeTimeStamp");
    String sequence = parameterMap.get("sequence");
    String product = parameterMap.get("product");
    String quantity = parameterMap.get("quantity");
    String price = parameterMap.get("price");
    if (exchange == null)
    exchange = "";
    if (messageType == null)
    messageType = "";
    if (traderTimeStamp == null)
    traderTimeStamp = "";
    if (exchangeTimeStamp == null)
    exchangeTimeStamp = "";
    if (sequence == null)
    sequence = "";
    if (product == null)
    product = "";
    if (quantity == null)
    quantity = "";
    if (price == null)
    price = "";

    You could first put "" for all potential keys.
    Or you could create a helper method
    public String nonNull(String s) {
      return (s != null) ? s : "";
    String exchange = nonNull(parameterMap.get("exchange"));

  • 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();
    }

  • Difference Between HashMap and HashTable

    Difference Between HashMap and HashTable
    Please explain with an example

    I have a situation in Java Collection and i am not
    able to figure a good solution. I am scared about the
    performance and memory that wil be used
    I have 5 List objects with thousands and thousands of
    records in it. The List is populated by a database
    query using jdbcTemplate which return like 200,000
    records
    Each record is identified by POLICY_ID. They may be
    List with multiple records for a POLICY_ID
    I want to extract each POLICY_ID from all the 5 List
    and make a single List object for each POLICY_ID and
    for each List and pass it to a print job which will
    print the data for a POLICY_ID
    Example
    Let say we have POLICY_ID = 15432
    List1 has one record for 15432
    List2 has one record for 15432
    List3 has one record for 15432
    List4 has three record for 15432
    List5 has three record for 15432
    From the 200,000 records in List1 i want to generate
    a seperate list with 1 record for policy id 15432 and
    let name is Listperpolicy
    after this logic we have
    Listperpolicy1
    Listperpolicy2
    Listperpolicy3
    Listperpolicy4
    Listperpolicy5
    call print job ( Listperpolicy1, Listperpolicy2,
    Listperpolicy3, Listperpolicy4, Listperpolicy5)
    Please let me know
    Thanks a Lotttttttttdon't worry about performance until you've got a working application. second-guessing what the performance bottlenecks will be is futile

  • Missing Value using HashMap and StringTokenizer

    class StringToken
         String Message = "a b Germany";
         HashMap <String,String> map;
    StringTokenizer token;
         public StringToken()
              try
              token = new StringTokenize(Message);
                   map = new HashMap <String,String>();
                   map.put("a","Adelaide");
                   map.put("b","Auckland");
    while (token.hasMoreToken())
                        System.out.print (map.get(pesan.nextToken())+" ");          
              catch(Exception e)
         public static void main(String[] args)
              new StringToken();
    The output like this :
    Adelaide Auckland null
    What i want like this:
    Adelaide Auckland Germany
    The problem is,How to display all value of Message? cos There's no Germany key..i want to make some condition like this, if there's no key in the Hashmap, the value still displayed originally..
    At my code the problem is, if there's no key in hashmap,output wont display the word..
    Thanks Guys...

    Two options:
    1) Instead of
    System.out.print(map.get(pesan.nextToken()));do
    String token = pesan.nextToken();
    String value = map.get(token);
    if (value==null) value = token;
    System.out.print(value);2) Implement a new Map which provides this behavior.
    Cheers

  • Get key values from HashMap

    Hi,
    I'm trying to get the values of the keys in my HashMap into a String array. Here is the code I'm using:
    HashMap row = new HashMap();
    row.put("A","Approved");
    row.put("D","Disapproved");
    row.put("P","Pending Approval");
    row.put("S","For Simulation Only");
    String[] key = new String[row.size()];
    int k=0;
    while (row.keySet().iterator().hasNext()) {
         key[k] = (String)row.keySet().iterator().next();
         k++;
    }What I'm getting:
    key[0] = "A"
    key[1] = "A"
    key[2] = "A"
    key[3] = "A"
    What I want is:
    key[0] = "A"
    key[1] = "D"
    key[2] = "P"
    key[3] = "S"
    Help, please!

    kd, I know that feeling...
    String[] keys = (String[]) row.keySet().toArray(new String[0]);
    In this case toArray will realize that the zero-length array
    is too short and create/return a new array containing objects
    of type String.Strictly speaking, if you don't give any array (toArray()), the array is an Object[], and as kd said, you can't cast to some other type.
    If you give an array of a specific type, you can cast. If that array is too small, the method will create a new array of the correct type. So you might as well pass it an array at least as big, since in this case you can tell how big it should be. This avoids allocating 2 arrays. Obviously the other will is likely to be GC'd, but why create it if not needed. Maybe that's too much of a micro optimization.

  • Get the values of hashmap in another class

    Hi All,
    i already posted this topic yesterday..But i did not get any helpful response..Kindly help me because I am new to java and I need some help regarding hashmap..
    I have a one value object java class which name is HashTestingVO.java
    *******************************************INPUT OF HashTestingVO.java***************************************
    public class HashTestingVO extends PersistentVO implements ILegalWorkFlowACLVO {
    public final static HashMap legalReviewPieceRelatedACLMap = new HashMap();
    legalReviewPieceRelatedACLMap.put("Futhure Path Check","ereview_acl_piece_related_cat1");
    legalReviewPieceRelatedACLMap.put("Send to Legal Review","ereview_acl_piece_related_cat1");
    legalReviewPieceRelatedACLMap.put("Review Precondition","ereview_acl_piece_related_cat1");
    Now i want to get the Hash Map values of this in another class called Testing.java class
    Ex: i need the value like this in Testing.java
    HashTestingVO obj=new HashTestingVO();
    obj.get(Futhure Path Check) -----------> I want to get the value of key1
    Public means you can access it another class..
    But Static means within the class we will use it...

    already posted this topic yesterday..But i did not get any helpful response..Kindly help me because I am new to java and I need some help regarding hashmap..I thing Exposing your dataStructure to any other class is not the right practise.
    You can make the Hashmap object private and nonstatic and provide a getter method in this class to get the value corresponding to any particular key.
    public Object getValue(String key)
      return egalReviewPieceRelatedACLMap.get(key);
    }

  • Retrieving all values from hashmap in order you put them in

    Hi guys,
    I want to retrieve all values from a HashMap in the order I put them in.
    So I can't use the values() method that gives back a collection and iterate over that.
    Do you guys know a good way to do that ?

    You can just do something like this:
    class OrderedMap
        private final Map  m_rep = new HashMap();
        private final List m_keys = new ArrayList();
        public Object get( final Object key )
            return m_rep.get( key );
        public Object put( final Object key, final Object value )
            final Object result = m_rep.put( key, value );
            if ( result != null )
                m_keys.add( key );
            return result;
        public Object remove( final Object key )
            final Object result = m_rep.remove( key );
            if ( result != null )
                m_keys.add( key );
            return result;
        public Iterator keyIterator()
            return m_rep.iterator();
    }Then use it like this:
       for ( Iterator it = map.keyIterator(); it.hasNext(); )
           final Object value = map.get( it.next() );
       }This will be in the order you put them in. However, if you want to do this correctly, you should implement the Map interface and add all the methods. Another thing you can do is download the JDK 1.4 source, learn how they did and do it the same way for 1.2.
    R.

  • Reading HashMap Values From a File

    Hi,
    I haven't done file I/O in quite a while, so I'm a little rusty.
    I have a HashMap<TreePath, Entity> that I need to store persistently. Thus far I have been creating a new HashMap every time a new session starts and populating it with Entity objects that I create from JDBC ResultSets. The TreePath is generated by adding each Entity object to its parent in the JTree. That all works well.
    Now I'm trying to write the HashMap to file using ObjectOutputStream. Basically I want to be able to load the JTree (which does not need to be persistent at this stage), and as I load it I get the TreePath of each TreeNode. If that TreePath is a key in the persistent HashMap, then I want to display the details stored in the corresponding Entity. However, when I try to read the HashMap using an ObjectInputStream, I get a NullPointer.
    I'm not sure whether the problem is in the way I'm trying to write or read the HashMap, or both. I've followed the examples in the API but they don't seem to be doing the job.
    Any suggestions?

    I have isolated the problem.
    HashMap<TreePath, Entity> map = memory.getMap();
    TreePath nodePath = new TreePath(node.getPath()); //where node is a DefaultMutableTreeNode
    System.out.println("1. Desired key is: " + nodePath);
    System.out.println("2. Map contains key: " + map.containsKey(nodePath));
    System.out.println("3. Keys in map: " + map.keySet().toString());When I use a volatile Java object to store the map, an example of the output produced by the following code is:
    1. Desired key is: [DW, Acct]
    2. Map contains key: true
    3. Keys in map: [[DW], [DW, Acct]]
    However, when I use file I/O to make the Java object permanent, an example of the output produced by the following code is:
    1. Desired key is: [DW, Acct]
    2. Map contains key: false
    3. Keys in map: [[DW], [DW, Acct]]
    As far as I can see, line 2 of the I/O output should be true, not false, since line 3 shows that the key is present in the map.
    Am I missing something here, or is the containsKey() method returning the incorrect result? It looks like it is getting its reference to map all wrong.

  • How to get all the values from a HashMap? thanks

    hi
    can anyone tell me how to get all the keys and their values contained in a HashMap? thanks

    thanks to u all for ur response, i gues if i need to get both keys and values, i need to use keySet() to get a set of keys first and then using each key to get value. is there any other faster way to get both of them (key and value)? thanks again

  • 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 get the value in a hashmap with a key of expression "123-456"?

    Hi all,
    I new to java and having a problem with getting values from a hashmap.here is the code which i wrote
    Map map = new HashMap();
    int m = 123;
    int n = 456;
    String key = String.valueOf(m) + "-" + String.valueOf(n);
        map.put(key, true);
        Now i am trying to get the value and i get an exception
    boolean b = map.get(String.valueOf(m) + "-" + String.valueOf(n));Can someone help me how to pass this expression as key in the hashamp

    Hi corlettk,
    Thanks for your reply. I have defined my map as Map<String, Boolean> selectedIds = new HashMap<String, Boolean>();
                selectedIds.put("123-456", true);           
                int m=123; int n=456;
                                     selectedIds.put(String.valueOf(m) + "-" + String.valueOf(n),true);
                boolean viv = selectedIds.get("String.valueOf(m)-String.valueOf(n)");
                System.out.println(viv);
                My problem is the hashmap key must be set dynamically ("123-456" is just an example) and when i get the value i should be able to pass those varibales in an expression correctly. Please let me know how can i pass an expression like the one above as a hashmap key. Please advise.

  • 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

  • Multiple query results in HashMap

    Hi,
    Can anybody tell me how I can store multiple results of a select query in a HashMap. I basically know how to do it but here is the problem:
    I want the table ids to be the keys and ArraySets containing database data to be the values of the HashMap. But whenever I add a new key/value pair to the HashMap all the values get overridden with the ArraySet I add.
    Here is my code:
    public HashMap getResults() throws Exception {
    Class.forName(org.gjt.mm.mysql.Driver);
    Connection con = DriverManager.getConnection(jdbc:mysql:///myDbName?user=user&password=password);
    HashMap hmResults = new HashMap();
    ArrayList alValues = new ArrayList();
    PreparedStatement preparedStatement = con.prepareStatement("select id, name, email from mytable");
    ResultSet resultSet = preparedStatement.executeQuery();
    if (resultSet != null) {
    while (resultSet.next()) {
    alValues.clear();
    alValues.add(resultSet.getString("id"));
    alValues.add(resultSet.getString("name"));
    alValues.add(resultSet.getString("email"));
    // the next line adds the correct key and value but also overrides all the other values in the HashMap, why?
    hmResults.put(resultSet.getString("id"), alValues);
    return(hmResults);
    The method above returns a HashMap containing the correct keys but the values are all the same.
    What am I doing wrong?
    Thanks for helping me out!

    Because your adding to the HashMap a reference to that ArrayList, not the ArrayList itself. So basically each key in your HashMap references the one ArrayList, which you repeatedly clear and update. In the end, all your keys map to the same reference, which will contain the very last information retrieved from the ResultSet.
    Simple fix... place the ArrayList alValues = new ArrayList() line inside your loop, and each key will be mapped to a different reference.

Maybe you are looking for

  • Disk Utility won't let me format external drive to FAT32

    Maybe this cannot be done or the answer is simple and I am missing it. I have a 1.5tb Maxtor drive hooked up via fw800. I want to have 120gb of this as Mac OS extended journaled to back up my internal drive via Time Machine. I want the other 1.38tb t

  • Bank Guarentees & Letter Of Credits

    Hi all hope evy body is doing good Guys i need a smal favourl ffrom all of u 1) what are the steps to be followed for The letter of credit & Bank guarentees Configuration 2) what is Audit information system(AIS) in SAP 3) And what is Joint Venture Ac

  • Service Entry Sheet table

    Hi all, Any anybody tell me which table i can get the short text, quantity, gross price, currency, cost center, net value for Service Entry Sheet? I tried in ESLL table with packeage number but all the above fields are cuming 0.00 in this table Regar

  • Launching PCR-Workflow from Backend in Portal

    Hello We have a PCR-scenario running (ESS+MSS) with EP 6.0 SP2 Patch 4 HF 7 und CM SP2 P4 HF5 and it works great in the uwl in the portal. But some of our people still prefere working in the Business Workplace ("UWL of the Backend") instead of the uw

  • Preventing

    "IllegalStateException: response already committed.:"       But not always--it's worked on occasion.           I open a connection to a database to do an INSERT, QUERY, and INSERT early on.      I go to a couple of static pages.      I then begin a s