HashMap cast

HashMap<Object, Object> parameters = (HashMap<Object, Object>) request.getParameterMap();
this.setRequestContextMap(new HashMap(parameters));
This is giving me
warning: [unchecked] cast.
warning: [unchecked] unchecked call to HashMap(java.util.Map<? extends K,? extends V>) as a member of the raw type java.util.HashMap
How do I get rid of this warning?
- J

specify type arguments for HashMap allocation:
e.g. new HashMap<Object,Object>(parameters)

Similar Messages

  • Java 7 update 51 cause the following error: java.util.HashMap cannot be cast to java.awt.RenderingHints

    Since I installed Java 7 update 51 accessing the EMC VNX Unisphere Console cause the following error: java.util.HashMap cannot be cast to java.awt.RenderingHints.
    I rolled back to Apple Java 1.6 -005 now I am getting the following error: plug-in failure.
    I think this is cused by the fact that the EMC console application has been written for java 7 and not java 6. Has anybody faced and solved the "java.util.HashMap cannot be cast to java.awt.RenderingHints." error ?

    Hi Yaakov,
    The error is thrown from the  eclipselink.jar:2.5.1 which is a JPA provider .
    Is the above jar bundled in the Oracle Product you are working upon or was this downloaded from external site ?
    If the jar is bundled with the Oracle Product, go ahead a log a SR with Oracle Support with Toplink product group to drill down on the issue, as the issue is happening internally or thrown by the Eclipselink implementation and we've no control....
    Hope it helps!!
    Thanks,
    Vijaya

  • Weblogic 10.3 error apache ListOrderedMap cannot be cast to java HashMap.

    Hi All,
    I'm having following code which is using spring(version: 2.0) dao
    public Map<String, String> getEmplyeeMap() throws Exception {     
              StringBuffer query = new StringBuffer("");
              query.append("select emp_name,dept_name from EMPLOYEE order by emp_no");
              logger.info("Inside getEmplyeeMap...Query to be executed :"+query.toString());     
              Map<String, String> EmpMap = new LinkedHashMap<String, String>();
              List<Map<String,String>> l_lstQueryRes = (ArrayList<Map<String,String>>)getJdbcTemplate().queryForList(query.toString());
              logger.info("l_lstQueryRes:"+l_lstQueryRes);
              if (l_lstQueryRes != null)
                   for (int l_iLoop = 0; l_iLoop < l_lstQueryRes.size(); l_iLoop++)
                        Map<String,String> l_mapRowData = new HashMap<String,String>();
                        l_mapRowData = (HashMap<String,String>)l_lstQueryRes.get(l_iLoop);                    
                        EmpMap.put(l_mapRowData.get("emp_name"), l_mapRowData.get("dept_name"));
                   }//End of for loop
              }//End of if loop          
              logger.info("EmpMap list size is.." + EmpMap.size());
              return EmpMap;
         } //End of getEmplyeeMap
    getting below error
    org.apache.commons.collections.map.ListOrderedMap cannot be cast to java.util.HashMap
    I'm thinking this problem is occurring because of jdk1.6 version, is anyone come across this problem?? This same working good in weblogic9.2 version.
    Thanks advance.
    Regards,
    Sharath.

    user9222505 wrote:
    Ok, thanks. So how do i determine where we are at since I have this "465"? How does that relate to a particular patch?
    Logger@9214443 3.5.3/465I believe, you are on 3.5.3 unpatched, and if I correctly remember, after applying the 3.5.3 patch 4 it should like like 3.5.3p4/... or 3.5.3.4/... (don't remember which one)... You would have to download that patch from your Oracle Support website (whichever you use), and apply the patch to a pristine extracted directory of 3.5.3 according to instructions in the patch zip.
    Starting with a recent version no more manual patching is necessary and you can download full distributions of patched versions from Oracle Support, but I don't think that applies to 3.5.3, yet (although it is possible that they recreated patch artifacts like that for earlir versions).
    If you do not have a support contract then you cannot download a patch or patched versions. You can only download a new full release which always has any previously released patches incorporated, though 3.5.3 is the last 3.5 full release if I correctly remember... and 3.6 comes with code incompatibilities at a few places so it is not a drop-in replacement...
    Best regards,
    Robert

  • Java.util.HashMap cannot be cast to org.apache.struts.action.ActionForm

    Hi!
    anybody could help me?
    i am getting java.util.HashMap cannot be cast to org.apache.struts.action.ActionForm error when I run my jsp...
    heres my code :
    CommentAction.java
    package com.provintl.rmis.actions;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import javax.sql.DataSource;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import com.provintl.rmis.forms.CommentForm;
    public class CommentAction extends Action {
         Statement stmt = null;
         Connection con = null;
         javax.sql.DataSource dataSource;
         PreparedStatement ps = null;
         ResultSet rs=null;
         byte updFlg = 0;
         Map commentlist = new HashMap();
         /* (non-Javadoc)
         * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
         @Override
         public ActionForward execute(ActionMapping mapping, ActionForm form,
                   HttpServletRequest request, HttpServletResponse response)
         throws Exception {
              CommentForm commentForm = new CommentForm();
              Date date = commentForm.getDaterecord();
              String comment = commentForm.getComment();
              //TODO : temporary 1 == rose
              int userID =1;
              int appID =1;
              String SelectQry = "SELECT "+
                                       "APPLICANT_TBL.CHFNAME, "+
                                       "APPLICANT_TBL.CHLNAME, "+
                                       "APPLICANT_TBL.INTAPPID, "+
                                       "USERHST_TBL.CHCOMMENT, "+
                                       "USERHST_TBL.DTDATECREATED, "+
                                       " USERHST_TBL.INTHSTID "+
                                       "FROM "+
                                       "APPLICANT_TBL "+
                                       "INNER JOIN USERHST_TBL ON (APPLICANT_TBL.INTAPPID = USERHST_TBL.INTAPPID) " +
                                       "WHERE APPLICANT_TBL.CHFNAME ='"+request.getParameter("first")+"' " +
                                                 "AND APPLICANT_TBL.CHLNAME ='"+request.getParameter("last")+"'";
              try {
                   dataSource = (DataSource)getDataSource(request, "RMIS");
                   con = dataSource.getConnection();
                   con.setAutoCommit(false);
                   stmt = con.createStatement();
                   System.out.println("database connected");
                   rs = stmt.executeQuery(SelectQry);
                   System.out.println("database connected");
                   int ctr = 1;
                   while(rs.next()){
                        commentlist.put(ctr,new CommentForm(rs.getString("CHFNAME"),rs.getDate("DTDATECREATED")));
                        ctr++;
                   if(updFlg !=0){
                        String insQry = "INSERT INTO RECRUIT.USERHST_TBL (CHCOMMENT, INTUSERID, INTAPPID)" +
                        "VALUES ('"+comment+"',"+userID+","+appID+")";
                        stmt.executeUpdate(insQry);
                        con.commit();
                        updFlg = 0;
                   HttpSession session = request.getSession();
                   session.setAttribute("commentlist", commentlist);
                   //con.setAutoCommit(true);
              } catch (SQLException se) {
                   System.out.println("We got an exception while preparing a statement:" +
                   "Probably bad SQL.");
                   System.out.println(SelectQry);
                   se.printStackTrace();
                   //System.exit(1);
              finally {
                   try {
                        rs.close();
                        stmt.close();
                        con.close();
                   } catch (SQLException e) {
                        e.printStackTrace();
              return mapping.findForward("comment");
    commentform.jsp
    =============
    <%@ taglib uri="http://jakarta.apache.org/struts/tags-html"     prefix="html"%>
    <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
    <%@ taglib uri="http://java.sun.com/jstl/sql_rt" prefix="sql"%>
    <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <script>
    function putLabel(lbl, formName){
    if (opener && !opener.closed){
    opener.document.addapp.jobposition.value=lbl;
    window.close();
    </script>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>List of open positions</title>
    </head>
    <body>
    <h2>Job Positions Available</h2>
    <%
    int ctr = 1; %>
    <logic:iterate id="myString" name="commentlist" scope="session">
    <table width="100%" border="0">
    <%
    String bakcolor;
    if((ctr % 2) == 0){
         bakcolor = "WHITE";
         ctr++;
    else{
         bakcolor = "SILVER";
         ctr++;
    %>
    <tr><td bgcolor="<%= bakcolor %>">
    <bean:write name="myString" property="value" />
    </td></tr>
    ${commentlist}
    </table>
    </logic:iterate>
    </body>
    </html>
    thank you in advance!

    Shilnag wrote:
    Hello guys,
    I am new to java... I am trying to develop a web application using
    1.Struts1.2
    2.tomcat 5.5
    3.eclipse 3.2.2Big mistake. Nobody new to Java should jump straight into webapps, let alone using a framework like Struts. Debatably, even Eclipse should be left alone.
    It's precisely because of this that you're having problems. Presumably you're following a tutorial or something, but - as demonstrated - as soon as it goes wrong, you're stuck. Learn some core Java first, trust me

  • Casting for HashMap

    Hi,
    I have a class called ThreadInfo:
    public class ThreadInfo{
              public ChatWindow threadID;
              public String ip;
              public String username;
              public boolean windowOpen;
              public boolean linkEstablished;
              ThreadInfo(){
                   windowOpen = false;
                   linkEstablished=false;
         }I also have a class:
    public class ServerStatus {
         private HashMap threadList;
         ServerStatus() {
              threadList = new HashMap();
    }now if I want to put a value in the HashMap, I would do:
    public void insertNewThread(String key, ThreadInfo info) {
              threadList.put(key,info);
         }right?
    and about retrieving a value, does this sound correct?
    public ThreadInfo getThread(String key){
              ThreadInfo requiredInfo = (ThreadInfo)threadList.get(key);
              return requiredInfo;
              }My query is really about this casting thing because in the API the get method returns an object, but since I know I am inserting a ThreadInfo class instance in the map, I thought that the casting here would give me the correct result.
    any insight to this is highly appreciated
    thanks,
    Talal

    Be careful doing this.
    HashMap can contain null as a value. null cannot be
    cast. Therefore you might want to test the value
    returned by get(key) for null before trying to cast it
    to your return type.
    matfudI do not believe the above is correct.
    Example:
    import java.util.*;
    public class Test68 {
        public static void main(String[] args) {
            HashMap hm = new HashMap();
            hm.put("aaa", null);
            String s = (String)hm.get("aaa");
            System.out.println(s);
            ArrayList al = (ArrayList)null;  // And just for the fun of it
    }C:\j2sdk1.4.0\Test>javac Test68.java
    C:\j2sdk1.4.0\Test>java Test68
    null
    C:\j2sdk1.4.0\Test>

  • Casting Hasble to Hashmap

    Hi All,
    Just wondering..
    Is it possible to do casting within Design Console. For instance, (Hashmap) Hashtable1

    Im using an Hashmap to keep float values:
    public HashMap qValues = new HashMap(10000,(float)0.75);
    qValues.put(p.hashCode(), new Float (v));
    ... p is a class of two different strings (Pair state/action). The hash code generated is the sum of the hash code of each different string
    v is the value i want to keep (Q value in Reinforcement Learning )
    Thanks for the reply:)

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

  • How to cast an object to a class known only at runtime

    I have a HashMap with key as a class name and value as the instance of that class. When I do a 'get' on it with the class name as the key, what I get back is a generic java.lang.Object. I want to cast this generic object to the class to which it belongs. But I don't know the class at compile time. It would be available only at runtime. And I need to invoke methods on the instance of this specifc class.
    I'm not aware of the ways to do it. Could anybody suggest/guide me how to do it? I would really appreciate.
    Thanks a lot in advance.

    Thanks all for the prompt replies. I am using
    reflection and so a generic object is fine, I guess.
    But a general question (curiosity) specific to your
    comment - extraordinarily generic...
    I understand there's definitely some overhead of
    reflection. So is it advisable to go for interface
    instead of reflection?
    Thanks.Arguments for interfaces rather than reflection...
    Major benefit at run-time:
    Invoking a method using reflection takes more than 20 times as long without using a JIT compiler (using the -Xint option of Java 1.3.0 on WinNT)... Unable to tell with the JIT compiler, since the method used for testing was simple enough to inline - which resulted in an unrealistic 100x speed difference.
    The above tests do not include the overhead of exception handling, nor for locating the method to be executed - ie, in both the simple method invocation and reflective method invocations, the exact method was known at compile time and so there is no "locative" logic in these timings.
    Major benefit at compile-time:
    Compile-time type safety! If you are looking for a method doSomething, and you typo it to doSoemthing, if you are using direct method invocation this will be identified at compile time. If you are using reflection, it will compile successfully and throw a MethodNotFoundException at run time.
    Similarly, direct method invocation offers compile-time checking of arguments, result types and expected exceptions, which all need to be dealt with at runtime if using reflection.
    Personal and professional recommendation:
    If there is any common theme to the objects you're storing in your hashtable, wrap that into an interface that defines a clear way to access expected functionality. This leaves implementations of the interface (The objects you will store in the hashtable) to map the interface methods to the required functionality implementation, in whatever manner they deem appropriate (Hopefully efficiently :-)
    If this is feasible, you will find it will produce a result that performs better and is more maintainable. If the interface is designed well, it should also be just as extensible as if you used reflection.

  • Dynamic cast at runtime (Here we go again! )

    Hy folks,
    today I read so many entries about dynamic casting. But no one maps to my problem. For a lot of them individual alternatives were found. And so I hope...
    Ok, what's my problem?
    here simplified:
    I have a HashMap with couples of SwingComponents and StringArray[3].
    The SwingComponents are stored as Objects (they are all JComponents).
    The StringArray comprised "the exact ClassName" (like "JButton" or "JPanel"),
    "the method, who would be called" (like "addItemListener")
    and "the ListenerName" (like "MouseMotionListener" or "ActionListener")
    At compiletime I don't know, what JCommponent gets which Listener.
    So a JPanel could add an ItemListener, another JPanel could add
    a MouseListener and an ActionListener.
    I get the description of the GUI not until runtime.
    The 'instanceof'-resolution is not acceptable, because there are above 50 listener. If I write such a class, I would write weeks for it, and it will be enormous.
    Now, my question
    I get the class of the Listenertype by
    Class c=Class.forName(stringArray[2]);
    and the method I'll call
    java.lang.reflect.Method method=component.getClass().getDeclaredMethod(s[1],classArrayOfTheParameter[]); //the parameter is not important here
    And I have a class, who implements all required ListenerInterfaces: EHP
    Now I wish something like this
    method.invoke((JPanel)jcomponent,(c)EHP);
    Is there anybode, who can give me an alternative resolution
    without instanceof or switch-case ?
    Greatings egosum

    I see, your right. Thanks. This problem is been solved.
    But a second problem is, that jcomponent can be every Swing-Object.
    I get the swing-component as Object from the HashMap . And I know
    what it is exactly by a String.
    What I need here is
    method.invoke(("SwingType")swingcomponentObject,Object[] args);
    I know, that this doesn't exist. Here my next question
    Can I take an other structure than HashMap, where the return value
    is a safety type (and not an Object). Or there are some other hints
    about similar problems and there resolutions?
    I don't like to write 50 (or even more than 50) "instanceOf"-instructions or "equal"-queries. And I'm not really interested in the whole set of java swing elements existing.
    I appreciate all the help I can get.
    With regards egosum

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

  • Why 2 castings in return statement of entrySet() of HashMap?

    Hi
    When looking through the code of the HashMap class in jdk 1.5 in Eclipse 3.2 I see the following:
    public Set<Map.Entry<K,V>> entrySet() {
    Set<Map.Entry<K,V>> es = entrySet;
    return (es != null ? es : (entrySet = (Set<Map.Entry<K,V>>) (Set) new EntrySet()));
    Here I am wondering why there in the return statement are 2 (two) castings:
    return (es != null ? es : (entrySet = (Set<Map.Entry<K,V>>) (Set) new EntrySet()));
    , where I think of (Set<Map.Entry<K,V>>) (Set)
    Can anyone give me a good explanation to this?
    Thank you!

    Hi,
    you're right: the casts are not really necessary at all, since an assignment from a raw type is possible without an explicit cast. Either with or without the casts, the compiler will issue an "unchecked" warning.
    (And, of course, a single cast to the target type would also work here.)
    The "correct" way to fix the code would be to make the inner class EntrySet a parameterized class by deriving it from AbstractSet<Map.Entry<K,V>>. Then all "unchecked" warnings would automatically disappear.
    My guess is that by the time the developer generified the HashMap, there where still compiler bugs preventing him from declaring inner classes such as EntrySet correctly. Since then, nobody's touched the code again.

  • Access values stored in 2D Array in HashMap

    Hi everyone i would like to know how to access values stored in a 2D array inside a HashMap
    Here is a drawing representation of the map.
    So to get the KEYS I just have to execute this code:
    this.allPeople = personInterests.keySet();But how can I get acces to the actual values inside the 2D Array?
    My goal is to create a treeSet and store all the elements of the first array in it, then look at the second array if any new elements are detected add them to the treeset, then third array and so on.
    I tried this code:
    Object[] bands = personInterests.values().toArray();
         for( int i=0; i<bands.length; i++)
              this.allBands.add(bands.toString());
    }But this.allBands.add(bands[i].toString())seems to be the problem, Dealing with a 2D array, this code only return a string representation of the Arrays and not a string representation of their elements.
    Using my logic I tried to execute:
       this.allBands.add(bands[0][i].toString());But i get a ARRAY REQUIRED BUT JAVA.LANG.OBJECT FOUND
    I really don't know the way to go.
    Thanks to anyone that will help.
    Regards, Damien.
    Edited by: Fir3blast on Mar 3, 2010 5:27 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    You'll just need to cast the object to the correct type. This is nothing to do with HashMap at all. If you don't know what that means then your google keywords are "java cast tutorial".

  • Order cannot be cast to com.tangosol.util.MapEvent

    This code is causing an exception. How should I be writing this filter? I want to listen for events when the status changes for one specific Order object. That Order has an integer key property which is the same integer key value used to store it in the cache. The code causing the exception is:
        public void addStatusChangeListener() {
                Filter f1 = new ValueChangeEventFilter("OrderStatus");
                Filter f2 = new EqualsFilter("Key", this.getKey());
                Filter f3 = new AndFilter(f1,f2);
                Filter statusChangeFilter = new MapEventFilter(MapEventFilter.E_UPDATED, f3);
                System.out.println("ADD STATUS CHANGE LISTENER "+this.symbol+" "+this.getKey());
                this.getCache().addMapListener(this , statusChangeFilter, false);
    2009-09-18 10:52:54.796/238.692 Oracle Coherence GE 3.5/459 <Error> (thread=DistributedCache, member=1):
    Exception occured during filter evaluation: MapEventFilter(mask=UPDATED, filter=
    AndFilter(ValueChangeEventFilter(extractor=.OrderStatus()), EqualsFilter(.Key(), 189000006))); removing the filter...
    2009-09-18 10:52:54.796/238.692 Oracle Coherence GE 3.5/459 <Error> (thread=DistributedCache, member=1):
    java.lang.ClassCastException: oms.Order cannot be cast to com.tangosol.util.MapEvent
            at com.tangosol.util.filter.ValueChangeEventFilter.evaluate(ValueChangeEventFilter.java:69)
            at com.tangosol.util.filter.AllFilter.evaluate(AllFilter.java:56)
            at com.tangosol.util.filter.MapEventFilter.evaluate(MapEventFilter.java:178)
            at com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.DistributedCache$Storage.prepareDispatch(DistributedCache.CDB:82)
            at com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.DistributedCache$Storage.postInvoke(DistributedCache.CDB:10)
            at com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.DistributedCache$Storage.invoke(DistributedCache.CDB:117)
            at com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.DistributedCache.onInvokeRequest(DistributedCache.CDB:50)
            at com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.DistributedCache$InvokeRequest.run(DistributedCache.CDB:1)
            at com.tangosol.coherence.component.net.message.requestMessage.DistributedCacheKeyRequest.onReceived(DistributedCacheKeyRequest.CDB:12)
            at com.tangosol.coherence.component.util.daemon.queueProcessor.service.Grid.onMessage(Grid.CDB:9)
            at com.tangosol.coherence.component.util.daemon.queueProcessor.service.Grid.onNotify(Grid.CDB:136)
            at com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.DistributedCache.onNotify(DistributedCache.CDB:3)
            at com.tangosol.coherence.component.util.Daemon.run(Daemon.CDB:37)
            at java.lang.Thread.run(Thread.java:619)Thanks,
    Andrew

    Ok, but isn't it just something wrong with how I wrote/used that filter?
    -Andrew
    public class Order implements Cloneable, Comparable, java.io.Serializable, MapListener {
        private String symbol = null;
        private OrderStatus orderStatus = OrderStatus.PENDING_NEW;
        private int id = 0; // java int max = 2,147,483,647
        private transient ArrayList<OrderStatusChangeListener> statusChangeListeners = new ArrayList<OrderStatusChangeListener>();
        public static NamedCache getCache() {
            if (cache == null) {
                System.out.println("Order...CacheFactory.getCache(\"orders\")");
                cache = CacheFactory.getCache("orders");
            return cache;
        public void send() {
            getCache().put(this.id, this);
        public static int sendMultiple(Iterable<Order> orders){
            int counter=0;
            HashMap m = new HashMap();
            for (Order o:orders){
                m.put(o.getKey(),o);
                counter++;
            getCache().putAll(m);
            return counter;
        public static class CancelProcessor extends AbstractProcessor {
            public Object process(InvocableMap.Entry entry) {
                Order o = (Order)entry.getValue();
                if (o.cancelCount == 0) {
                    o.cancelCount = 1;
                } else {
                    logger.info("ignoring dup. cancel req on " + o.symbol + " id=" + o.id);
                return o.cancelCount;
        public void cancel() {
            Filter f = new EqualsFilter("getCancelCount", 0);
            UpdaterProcessor up1 = new UpdaterProcessor("setCancelCount", new Integer(1));
            UpdaterProcessor up2 = new UpdaterProcessor("setCancelSubmittedTime", Base.getSafeTimeMillis() );
            CompositeProcessor cp = new CompositeProcessor(new InvocableMap.EntryProcessor[] {up1,up2});
            ConditionalProcessor x = new ConditionalProcessor(f, cp);
            getCache().invoke(key, x);
        private static NumberIncrementor ni1 = new NumberIncrementor("CancelCount", 1, false);
        public static void cancelMultiple(Collection<Integer> orderIds){
            getCache().invokeAll(orderIds, ni1);
        public static void cancelAllByAccount(String account){
            getCache().invokeAll( new EqualsFilter("getAccount", account), ni1);
        public void cancelAllowingMultipleCancelsOfThisOrder() {
            System.out.println("cancelAllowingMultipleCancelsOfThisOrder symbol=" + symbol + " key="+key+ " id=" + this.id);
            getCache().invoke(key, ni1);
            UpdaterProcessor up = new UpdaterProcessor("setCancelSubmittedTime", Base.getSafeTimeMillis() );
            getCache().invoke(key, up);
        public void entryInserted(MapEvent mapEvent) {
        public void entryUpdated(MapEvent mapEvent) {
            Order o = (Order)mapEvent.getNewValue();
            fireStatusChange(o);
        public void entryDeleted(MapEvent mapEvent) {
        public void removeStatusChangeListener(OrderStatusChangeListener listener) {
            synchronized (statusChangeListeners) {
                statusChangeListeners.remove(listener);
                if (statusChangeListeners.size()==0) {
                    this.getCache().removeMapListener(this, statusChangeFilter);
        private transient Filter statusChangeFilter=null;
        public void addStatusChangeListener(OrderStatusChangeListener listener) {
            if (statusChangeFilter==null) {
                Filter f1 = new ValueChangeEventFilter("OrderStatus");
                Filter f2 = new EqualsFilter("Key", this.getKey());
                Filter f3 = new AndFilter(f1,f2);
                statusChangeFilter = new MapEventFilter(MapEventFilter.E_UPDATED, f3);
            System.out.println("ADD STATUS CHANGE LISTENER "+this.symbol+" "+this.getKey());
            synchronized (statusChangeListeners) {
                if (statusChangeListeners.size()==0) {
                    this.getCache().addMapListener(this , statusChangeFilter, false);
                statusChangeListeners.add(listener);
        private void fireStatusChange(Order o ) {
            System.out.println("FIRE STATUS CHANGE: starting...");
            // do not depend on the firing of a status change to mean that the
            // status did certainly change.  Use the firing of status change as a
            // trigger to examine the order's status w/getStatus().
            System.out.println("1");
            synchronized (statusChangeListeners) {
                System.out.println("2");
                List<OrderStatusChangeListener> asdf = new LinkedList<OrderStatusChangeListener>(statusChangeListeners);
                System.out.println("3");
                for (OrderStatusChangeListener x : asdf) {
                    System.out.println("4");
                    try {
                        System.out.println("FIRE STATUS CHANGE: "+x);
                        x.dispatchOrderStatusChange(o);
                    } catch (java.util.ConcurrentModificationException e) {
                        logger.error("** fireStatusChange: ConcurrentModificationException " + e.getMessage());
                        logger.error(e.getStackTrace());
                        e.printStackTrace();
            System.out.println("FIRE STATUS CHANGE: done...");
        public int compareTo(Object o) { //assumes ID allways int.
            return this.key - ((Order)o).key;
        public boolean equals(Object o) {
            return (this.key == ((Order)o).key);
        public void setStatus(OrderStatus orderStatus) {
            this.orderStatus = orderStatus;
        public OrderStatus getStatus() {
            return orderStatus;
        public Integer getKey(){
            return key;
        private Integer key;
        public Order() {
            id = generateId();
            key=new Integer(id);
        public Object clone() {
            try {
                Order order = (Order)super.clone();
                order.setId(order.generateId());
                return order;
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            return null;
        public static int generateId() {
            idwLock.lock();
            try {
                if (nextId == flipOverId) {
                    // redo this w/a number incrementor passing in null for the member variable
    //                ValueManipulator vm=null;
    //                NumberIncrementor ni = new NumberIncrementor(vm, 1, false);
                    NamedCache omsCache = CacheFactory.getCache("oms");
                    omsCache.lock("high_order_id");
                    Integer i = (Integer)omsCache.get("high_order_id");
                    if (i==null) i=188; // change to 1 once legacy is gone
                    omsCache.put("high_order_id", ++i);
                    omsCache.unlock("high_order_id");
                    flipOverId = (i+1) * MAX_ORDERS_PER_TRADER_ID;
                    nextId = (MAX_ORDERS_PER_TRADER_ID * i)+1;
                    return nextId;
                } else {
                    return ++nextId;
            } finally {
                idwLock.unlock();
        public boolean isCancelRequestedOrIsCanceled() {
            // change to cancelrequested lock, not ack lock
            if (orderStatus==OrderStatus.CANCELED)
                return true;
            //  ValueExtractor extractor = new ReflectionExtractor("getCancelCount");
            //  int cc = (Integer)cache.invoke( this.ID , extractor );
            Order o = (Order)getCache().get(this.id);
            int cc = o.getCancelCount();
            return cc > 0 || o.orderStatus == OrderStatus.CANCELED;
        public void setId(int Id) {
            this.id = Id;
        public int getId() {
            return id;
    }

  • When should object casting be used?

    Hi,
    just wondering something. Saw there that returning objects from methods and downcasting the returned object is bad. When should casting be used? I currently have a program that has an object that contains a HashMap as a field. When I try retrieve objects from the HashMap using the relevant key, I have to cast them to what they were originally! Is this bad programming practice or is it the only way to do things?
    Thanks.
    // example of retrieving object from key
    dbDirectory = (String)dbInfo.get("dbDirectory");

    LeWalrus wrote:
    Hi,
    just wondering something. Saw there that returning objects from methods and downcasting the returned object is bad. When should casting be used? I currently have a program that has an object that contains a HashMap as a field. When I try retrieve objects from the HashMap using the relevant key, I have to cast them to what they were originally! Is this bad programming practice or is it the only way to do things?
    Thanks.
    // example of retrieving object from key
    dbDirectory = (String)dbInfo.get("dbDirectory");
    Before generics, this was a perfectly acceptable practice. Generally speaking, you use type-casting when the compiler is unable to ensure the type validity at compile-time, but you know it is correct, so you supply the extra information to the compiler so it knows everything is correct. Sometimes you need to circumvent the strong type-checking part of the language for flexibility, but this is something that should be used very sparingly.
    Now it would be better to use generics so that the compiler will know at compile time that the values in your map are Strings, instead of just Objects.

  • Updating objects in a HashMap

    I have a HashMap and I need to write a method that updates certain field in the objects stored in it.
    I basically need to access random objects in the map and call a set method in the object to set a field to a specific value.
    How do I access the objects in the map and (presumably) cast them as their real class then call a method?
    Any ideas?

    the code i gave you should work without any mods...well, i mean, you don't have to worry about "putting" it back in the hashmap cuz it will be changed when you call someMethod() on it...
    remember, objects are pass by reference
    (or as some argue, pass by value where the value happens to be a reference... but i digress)

Maybe you are looking for