Doubt in Hashmap key

Hi All,
I have got few long in HashMap as key. So in my code I wrote
long temp= Long.parseLong((String)tempmap.get(key)But at this time Iam getting number format exception but when I do
long temp= String.valueOf(tempmap.get(key))it works fine.The above is a pseudo code and not right way of extracting key-value from hashmap. My question as hashmap key is an object
and casting it to String and then Long.parseLong fails but String.valueOf succeeds why?
How both treat objects differently.
Thanks for the advice in advance

My actual code was
Map.Entry ent=(Map.Entry)itr.next();
Long.parseLong(String.valueOf(ent.getKey()))
The key is a long. I just wrote a pseudo code and not exact code as my doubt why when I do
Map.Entry ent=(Map.Entry)itr.next();
Long.parseLong((String)(ent.getKey())) it fails but the first code gives results.So how String casting and String.valueOf treats object.

Similar Messages

  • Basic doubt about Primary Key/Foreign Key in Oracle Tables

    Hi,
    I have a doubt whether Primary Keys/Foreign Keys are allowed in Oracle. Some of the people I know are telling me that Oracle does not encourage having Primary Keys/Foreign keys in its database tables.
    However if I go to the ETRM and look for information about some of the Oracle Tables, I am informed that Primary Keys do exist. However I am being told that ETRM is not a reliable way of having correct information about table structure.
    It would be great if any one of you provides me with some insight in this. Any pointers to a document would be great.
    Thanks

    It is not that PK/FKs are disallowed in Oracle Apps (there are some on the standard Oracle Apps tables), but they are typically not used. I am not positive what the logic behind this is, but my guess is that it was party due to the earlier versions of Oracle Apps pre-dating declarative database referential integrity in Oracle DB and also on performance issues with the standard referential integrity with the earlier versions of declarative database referential integrity.
    As far as eTRM is concerned - I understood that the data is based on a design repository rather than a physical Oracle Apps DB. So all of the information in there is logically correct, but not necessarily enforced via the standard Oracle DB declarative referential integrity (rather by the application code or APIs).

  • Issue with passing expression to a hashmap key in a dataTable column

    hi all,
    Can someone help me with passing an expression like "123-456" to a hashmap key in my dataTable . In my dataTable i have t:columns tag which generates checkboxes for each row in the dynamic column .The value of checkbox must be identified by a combination of userID and accountID. So i want to set value of checkbox something like this'userID-account.ID' . But it never returns the right value since userID is taken as string instead i want the value of userID to be passed in that expression. Someone please help...iam struck with this issue from so long.Here is the code.
    page1.jsp:
    <t:dataTable id="groupuserlist"
                  var="user"            
                             value="#{manageuserscontroller.userList}"     // this is a list of userIDs
                 cellspacing="0"
                 preserveDataModel="false"
                 headerClass="topRow"
                 preserveSort="true"
                 summary="This table displays list of users for an accessgroup">
         <t:column>
          <f:facet name="header"><h:outputText value="User ID" /></f:facet>
          <t:outputText value="#{user.ID}" />
         </t:column>
         <t:column>
          <f:facet name="header"><t:commandSortHeader columnName="title" arrow="true"> <h:outputText value="Title"/> </t:commandSortHeader> </f:facet>
          <t:outputText value="#{user.title}" />
         </t:column>
          <t:columns var="cols" value="#{manageuserscontroller.selectedAGList}"> //selectedAGList is a list of accountIDs
          <f:facet name="header"><h:outputText value="#{cols.name}" /></f:facet>
          <h:selectBooleanCheckbox id="checkbox4" value="#{manageuserscontroller.selectedUserIds['user.ID-cols.ID]}" />
          </t:columns>
    </t:dataTable>Backing bean: In this selectedUserIds iam intentionally setting up key something like "userID-accountID" so that i can split the userID and accountID for later user
    private Map<String, Boolean> selectedUserIds = new HashMap<String, Boolean>();
             somebody please to my email. If you need further information iam very happy to provide any time. Also let me know if there is another way to get this job done..
    Thanks very much in advance

    Hi BalusC,
    I am very much thankful to you. I got my issue resolved only when i select one dynamic column. It doesn't seem to be working if i select multiple columns. Not sure where exactly my logic is going wrong. Here is a snippet of my code.. Please let me know if you find any mistake in it..Once again thanks very much..for your great help.
    jsp:
    <t:dataTable id="grouplist"
                  var="user"            
                   value="#{manageuserscontroller.userList}"     
                   styleClass="companyAdminMainTable ltgreen_Hrule marVertSml"
                 cellspacing="0"
                 preserveDataModel="false"
                 headerClass="topRow"
                 preserveSort="true"
                 summary="This table displays list of users for an account">
         <t:column>
          <f:facet name="header"><h:outputText value="User ID" /></f:facet>
          <t:outputText value="#{user.ID}" />
         </t:column>
         <t:column>
          <f:facet name="header"><t:commandSortHeader columnName="title" arrow="true"> <h:outputText value="Title"/> </t:commandSortHeader> </f:facet>
          <t:outputText value="#{user.title}" />
         </t:column>
          <t:columns id="dynamic" var="cols" value="#{manageuserscontroller.selectedAGList}">
          <f:facet name="header"><h:outputText value="#{cols.name}" /></f:facet>
          <h:selectBooleanCheckbox id="checkbox4" value="#{manageuserscontroller.selectedAGUserIds[user.ID][cols.accessGroupID]}" />
          </t:column>
          </t:columns>
    </t:dataTable>Backing bean:
    private Map<Integer, Map<Integer,Boolean>> selectedAGUserIds = new HashMap<Integer, Map<Integer,Boolean>>();
        private Map<Integer, Boolean> selectedAGIds = new HashMap<Integer, Boolean>();
    for(int j=0; j< selectedAGList.size(); j++){   //List of selected dynamic account columns
             for(int i=0; i < userList.size();i++){              // lisf of users
                   try {
                        int m = userList.get(i).getID();
                        int n = selectedAGList.get(j).getAccessGroupID();
                        selectedAGIds=(AccessGroupDAO.getUserMap1(userList.get(i).getID(),selectedAGList.get(j).getAccountID()));
                        selectedAGUserIds.put(userList.get(i).getID(),selectedAGIds);
                       System.out.println("hashmap value"+ selectedAGUserIds.get(m).get(n));
                        } catch (Exception e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                 System.out.println("outer hashmap size"+ selectedAGUserIds.size());
          }DAO:
    public static Map<Integer,Boolean> getUserMap1(Integer userID, int accountID) throws Exception {
         Map<Integer, Map<Integer,Boolean>> selectedUserAGIds = new HashMap<Integer, Map<Integer,Boolean>>();
                    Map<Integer, Boolean> selectedAGIds = new HashMap<Integer, Boolean>();
          String sql="  select iusermetaid,iaccountid from useraccountlist where iusermetaid = userID and iaccountid = accountID ";
             ResultSet rs = executeSQL(sql);
             if(rs!=null & rs.next()){
                  System.out.println("record found");
                  Integer aid = rs.getInt("iaccountid");
                        selectedAGIds.put(aid, true);
             else{
                  System.out.println("record not found");
                  selectedAGIds.put(accessGroupID, false);
                  System.out.println("get the key value"+ selectedUserAGIds.get(userID).get(accessGroupID));
            System.out.println("Exiting accessgroupDAO");
             return selectedAGIds;
    }

  • Problem using dynamic variable as HashMap key

    I have created a HashMap called instantHashMap and loaded it with data from a query.
    I can load a variable with a value for the HashMap key and successfully output the HashMap value:
    <c:set var = "gameno" value="150" />
    <c:out value = "${instantHashMap[gameno]}" />
    But when I load my variable value from my data like this...
    <c:set var = "gameno" value="${rvo.gameNo}" />
    <c:out value = "${instantHashMap[gameno]}" />
    ...it doesn't work.
    My loaded variable value is correct because this statement does work and reflects the data obtained from my query:
    <c:out value = "${gameno}" />
    Could rvo.gameNo be the wrong data type or something?

    My loaded variable value is correct because this statement does work >and reflects the data obtained from my query:In which case, check if your map contains a key which is the loaded variable value.
    ram.

  • Basic doubt about Primary Keys/Foreign Keys in Oracle Tables

    Hi,
    I have a doubt whether Primary Keys/Foreign Keys are allowed in Oracle or not. I have been informed that Oracle does not encourage having Primary Keys/Foreign keys in its database tables. Instead it urges users to have unique constraints on the requisite columns.
    However if I go to the ETRM and look for information about some of the Oracle Tables, I am informed that Primary Keys do exist. At the same time, I am being told that ETRM is not a reliable way of having correct information about table structure (at least the Primary Key information).
    It would be nice if any one of you provides me with some insight in this. Any pointers to a document would be welcome.
    Thanks

    FYI,
    There is seprate forum for Core Sql quieries
    PL/SQL
    Thanks

  • HashMap keys and values not staying consistent (my fault, but why?)

    Alright, after starting out for the very first time with HashMaps a few hours ago, I've gotten the hang of them decently I think. I am encountering a problem, though, when I try to get user-selected keys + values to display. My code is:
       public void useZone(String use)
           Object used = hm.get(use);
           System.out.print("\f");
           Set set = hm.entrySet();
           Iterator i = set.iterator();
           if (used != null){
               System.out.println("Time Zone Used:");
               Map.Entry thiszone = (Map.Entry)i.next();
               Object usedzone = thiszone.getValue(); //Get the value of the zones and assign them as Object usedzone
               Integer useval = (Integer) usedzone; //Assign the Object to an Integer value so we can use it
               difference = useval;
               if (useval > 0){ //Display the hour offset correctly
                   System.out.println(use + ": GMT +" + usedzone.toString());
               else if (useval == 0){
                   System.out.println(use + ": GMT");
               else if (useval < 0){
                   System.out.println(use + ": GMT " + usedzone.toString());
           else{
               System.out.println("Invalid zone name.");
           } //End if
           ClockDisplay.getZone(difference); //Send variable difference
      }What will happen is that the first time I will be fine...
    Say the HashMap keys and values are
    "Rome", "-2"
    "Chicago", "6"
    "New York", "5"
    "Paris", "-1"
    If I type "Rome" in when I execute this method, it gives me the correct output - "Rome: GMT -2"
    If I then re-run the method, as to display a different one, I get "Chicago: GMT -2"
    It's like the name the user inputs is updating, obviously, but the value of the HashMap that goes along with the user-input doesn't match up or something. My code is confusing myself after looking at it for nearly 10 hours, so I apologize that I had to post something so trivial here - I'm sure it's just a problem with my wordings....any help would be greatly appreciated.

    Hello,
    It's very possible I'm missing some things here, but I've attempted to review your code.
    Let me just define the specs of the code as I see them:
    Method useZone accepts String input, which is "supposed" to be the key to a hashmap.
    The timezone offsets are the value's in this hashmap.
    The value is of type Integer.
    If a key is properly selected, print out GMT + or - the offset?
    If I have this correct, consider the following implementation:
       public void useZone(String use) {
           Integer offset = (Integer)hm.get(use);
           System.out.print("\f");
           if (offset != null){
               System.out.println("Time Zone Used:");
               System.out.println(use + ": GMT +" + offset.toString());
           } else{
               System.out.println("Invalid zone name.");
           ClockDisplay.getZone(offset); //Send variable difference
      }I'd guess you're getting odd behavior because you're creating an iterator to iterate through the map, but then only calling i.next() once - HashMap doesn't guarantee insertion order, so the fact it worked once correctly is "random".
    Also, if you are using java 1.5 declare the map as follows:
    Map<String, Integer> hm = new HashMap<String, Integer>();And you can get rid of the casts. I would also suggest renaming the hashmap to something that describes what it holds, rather than it's object type. Maybe something like timeZoneMap - or offsetMap. I would also consider renaming "use" to something that describes the data it might hold, instead of something that describes the workflow.
    Variable naming is very difficult! I would suggest renaming all of your variables, but I think those are the only ones I kept!
    Edited by: Adam_Schaible on Nov 28, 2007 12:09 PM

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

  • Strings as hashmap keys

    If I use a string (a file name, for example) as the key for a hashmap put call, and then later try to retrieve the stored object using the same string, but this time hard-coded, will my object be retrieved? That is, will the dynamically loaded key and the hard-coded key be seen as the same object?
    that is ...
    image is read in from a file
    image is stored in hashmap, using filename as key
    retrieval is attempted using image title "image.gif" - is it successful?

    Do you mean this? String key = getStringSomehowSuchAsFielname();
    map.put(key, value);
    value = map.get("image.gif"); // I put with a variable but retrieve with a constant, so will it work?If that's what your'e asking, then yes, it will work. As long as the object that you use for a key properly overrides equals and hashCode, then it can be used as a key in a Map.
    "Properly overrides..." means that the state of the object is used the way you want it to be used for determining equality. In the case of java.lang.String, they're overriden the way you'd expect--i.e., using the sequence of characters in the string to determine equality.
    Make sense?

  • Vector as a HashMap key

    Hi all, I want to use Vector position as a key of hash map. Do you think that it is work? And could you mind show me some sample code. Thanks!!!

    It'll work. Here's some code that follows. However, in my sample, I'd rather store 'user' as the key to the HashMap. Also, the code below won't allow for the list to be sorted or anything after it is added to the HashMap.
    import java.util.*;
    public class VectorAndHashMap
        static class Preference
            String color;
            String fontSize;
            public Preference(String _color, String _fontSize) {
                color=_color;
                fontSize=_fontSize;
            public String toString() {
                return color+"/"+fontSize;
        public static void main(String[] args)
            Object[] users = {"smith", "brown", "jones"};
            // create the Vector
            Vector v = new Vector(Arrays.asList(users));
            Object[] prefs = { new Preference("blue", "big"),     // smith's
                               new Preference("blue", "small"),   // brown's
                               new Preference("red", "medium") }; // jones's
            // create the HashMap
            HashMap hashmap = new HashMap();
            // load the HashMap
            for(int i=0; i<v.size(); i++)
                hashmap.put(new Integer(i), prefs);
    // lookup index for "brown"
    int j=0;
    boolean found = false;
    for(j=0; j<v.size(); j++) {
    String user = (String)v.get(j);
    if(user.equals("brown")) {
    found = true;
    break;
    // retrieve record
    if(found) {
    Preference pref = (Preference)hashmap.get(new Integer(j));
    System.out.println("brown's record: " + pref);

  • Doubt with PRIMARY KEY in sql!

    Dear friends,
    Can you please explain me this scenario's problems
    create table a ( eno number);
    alter table a add( eno1 number primary key);
    alter table a drop primary key;when i describe the table still the column eno1 is showing as NOT NULL. and i cannot modify it as NULL also by sayin
    alter table a modify ( eno1 null);is it s a problem with oracle itself or have i understood the concepts wrong.
    Regards,
    Manoj

    bluefrog --
    Did you repeat the OP's test case exactly? Here is both yours and the OP's on an 11.2.0.2 system and they behave differently.
    SQL> create table a(eno number primary key);
    Table created.
    SQL> desc a;
    Name                                                                                      Null?    Type
    ENO                                                                                       NOT NULL NUMBER
    SQL> alter table a drop primary key;
    Table altered.
    SQL> desc a;
    Name                                                                                      Null?    Type
    ENO                                                                                                NUMBER
    SQL> select * from v$version;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    PL/SQL Release 11.2.0.2.0 - Production
    CORE    11.2.0.2.0      Production
    TNS for Solaris: Version 11.2.0.2.0 - Production
    NLSRTL Version 11.2.0.2.0 - Production
    5 rows selected.
    SQL> drop table a purge;
    Table dropped.
    SQL> create table a(eno number);
    Table created.
    SQL> alter table a add( eno1 number primary key);
    Table altered.
    SQL> desc a;
    Name                                                                                      Null?    Type
    ENO                                                                                                NUMBER
    ENO1                                                                                      NOT NULL NUMBER
    SQL> alter table a drop primary key;
    Table altered.
    SQL> desc a;
    Name                                                                                      Null?    Type
    ENO                                                                                                NUMBER
    ENO1                                                                                      NOT NULL NUMBER
    SQL>

  • Doubt with primary key

    How can we update the primary key column in the master table and referential integrity in the child table ,
    while i am deleting the master table column i am having this error...
    update item_master set item_id=replace(item_id,322,007)
    ERROR at line 1:
    ORA-02292: integrity constraint (CMMS_MCO.SYS_C005568) violated - child record found
    anyone please reply me about this error...

    Hi,
    Why don't you just disable the foreign key constraint?
    TEST@XE> create table parent (id number constraint pk_parent primary key);
    Table created.
    LEGATTI@XE> create table child (id number constraint fk_child_parent references parent);
    Table created.
    LEGATTI@XE> insert into parent values (1);
    1 row created.
    LEGATTI@XE> insert into child values (1);
    1 row created.
    LEGATTI@XE> commit;
    Commit complete.
    LEGATTI@XE> update parent set id= replace(id,1,2);
    update parent set id= replace(id,1,2)
    ERROR at line 1:
    ORA-02292: integrity constraint (LEGATTI.FK_CHILD_PARENT) violated - child record found
    LEGATTI@XE> alter table child disable constraint fk_child_parent;
    Table altered.
    LEGATTI@XE> update parent set id= replace(id,1,2);
    1 row updated.
    LEGATTI@XE> update child set id= replace(id,1,2);
    1 row updated.
    LEGATTI@XE> alter table child enable constraint fk_child_parent;
    Table altered.
    LEGATTI@XE> select * from parent;
            ID
             2
    LEGATTI@XE> select * from child;
            ID
             2Cheers
    Legatti

  • Doubt in hashmap?

    we may have many null keys in hashmap

    But not "many", as the OP seems to be (?) asking...Yeah I tried to guess what the OP was asking and picked a question for him / her :o)
    If the OP had been meaning whether it is possible to have multiple null keys simultaneously in the same map, then obviously the answer would be no.
    Hopefully the OP didn't mean that though - as thats just crazy :o)

  • 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 get first item of hashMap w/out knowing the key

    Hi
    can someone tell me if there is a way to get first item from a hashMap when you dont know what the key is. as the get method expects a defined 'key'
    reason I am asking this:
    I am using struts 2 UI <s:radio> tag. this tag takes a hashmap and creates radio maps. it has a 'value' attribute and if something is passed to this attribute then that radio button is checked by default. the list that contains radio buttons is created dynamically so i dont know what is actually in the hashMap key's. but i do know that key's are string.
    so just wondering if there is a way to get first item from a hashmap without knowing the key...

    thanks for the quick reply.
    posted in java forums because thought it was a java API/workaround question. gave a little history because i didnt want people to start questioning my use of HashMap for this purpose..
    anywhose..i've found a workaround.
    If someone has a similar problem:
    as the hashmap is being populated dynamically....set a String member of class to contain the first key thats being put in the hashmap. then have struts tag pick up that value.
    also, through your post and reading hashMap api...its usefull to know that hasMaps do not gurantee the order of elements in it. So now I am using a TreeMap.
    Thanks

  • Requirement for object key for HashMap

    Hi,
    I would like to put the object to HashMap keyed by my own object. what is the requirement for the class to be key? I have a method boolean equals(Object o) defined in the key class, My key is composed by 2 ids, so in the equals method I compared the 2 ids. but it seems can't get the value out. Please help. Thanks

    How do I supposed to do the hashCode? If myKey1.equals(myKey2) returns true, then myKey1.hashCode() must return the same value as myKey2.hashCode(). One consequence of this is that if something is not used to compuate equals(), then it must not be used to compute hashCode(). (Note that the reverse is not true. That is, if two objects are not equal, they can still return the same value from hashCode(), and hence, if some data is used for equals() it may still be left out of hashCode().)
    You want hashCode to be 1) quick & easy to compute and 2) "well distributed" or "mostly unique. If you know how hashcodes are used (in the general sense, not just the Java hashCode() method) then you should understand why those properties are desirable. If not, just ask.
    The most common approach is to use some subset of the object's fields in computing the hashCode. If you have a Person object with lastName, firstName, birthdate, height, weight, address, phone number, you probably wouldn't use all those fields. You could just lastName, or maybe a combination of lastName and firstName.
    One generally combines multiple pieces by taking XORing (the "^") operator the individual pieces (for primitives) or their hashcodes (for objects). For example, in the Person example: public int hashCode() {
        return lastName.hashCode() ^ firstName.hashCode(); // but make sure to check for null first
    }

Maybe you are looking for

  • Apple Tv (3rd Gen) On screen keyboard US Version/UK Version

    I have recently bought the Apple tv from Amazon UK and was supplied with the US version, and I guess the only difference is the power cord ? What I would like to know is on some of the on screen keyboard down the bottom right you have .com .au etc (S

  • Help!  WDS mode Airport Express Ethernet port

    Hi: I just bought a LaCie ethernet disk mini. The info on the Lacie page said you could use it wirelessly by conecting it to the airport. I curently have my airport in the living room and an airport express in my own room. The airpot express is used

  • 2 different ipods, can't connect 1 of them

    Hi, About 2 weeks ago I bought the 2 gig Nano. I got that up and running just fine. I put my CDs on it, I bought a few CDs from iTunes and got those on it, and I even put some podcasts and photos on there. It was all quite easy, no problems at all. T

  • Is using Sybase Rep Server with SAP HANA a possibility?

    We have a customer has system that they are already using Sybase Replication Server.  They are asking to add HANA and BusinessObjects BI Platform as a sidecar, to there system and remove the Java applications they are using for reporting.  They are w

  • [FLMX] Efecto paso de hojas

    Hola. Se que apareció varias veces hace tiempo... Podéis decirme de algún código fuente de ejemplo para obtener el efecto del paso de hojas de un libro? Gracias.