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:)

Similar Messages

  • 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

  • Newbie - JSP & bean shopping cart logic error?

    Hello,
    I am attempting to bulid a shopping cart facility on a JSP site that I am building.
    I am having difficulties adding an item to the basket.
    The page below (bookDetail.jsp) displays items for sale from a database. At the foot of the page, I have set up a hyperlink to add an item to a basket bean instance created in this page.
    What happens is the page will load correctly, when i hover the mouse over the hyperlink to add the item to the basket, the status bar shows the URL of the current page with the details of the book appended. This is what I want. But when I click the link, the page will only reload showing 20% of the content.
    Netbeans throws up no errors, neither does Tomcat, so I am assuming I have made a logical error somewhere.
    I have enclosed the Book class, and the ShoppingCart class for your reference.
    Any help would be really appreciated as I am at a loss here.
    Cheers.
    Edited highlights from bookDetail.jsp
    //page header importing 2 classes - Book and ShoppingCart
    <%@ page import="java.util.*, java.sql.*, com.shopengine.Book, com.shopengine.ShoppingCart" errorPage="errorpage.jsp" %>
    //declare variables to store data retrieved from database
    String rs_BookDetail_bookRef = null;
    String rs_BookDetail_bookTitle = null;
    String rs_BookDetail_author = null;
    String rs_BookDetail_price = null;
    //code that retrieves recordset data, displays it, and places it in variables shown above
    <%=(((rs_BookDetail_bookRef = rs_BookDetail.getString("book_ref"))==null || rs_BookDetail.wasNull())?"":rs_BookDetail_bookRef)%>
    <%=(((rs_BookDetail_author = rs_BookDetail.getString("author"))==null || rs_BookDetail.wasNull())?"":rs_BookDetail_author)%>
    <%=(((rs_BookDetail_bookTitle = rs_BookDetail.getString("book_title"))==null || rs_BookDetail.wasNull())?"":rs_BookDetail_bookTitle)%>
    <%=(((rs_BookDetail_price = rs_BookDetail.getString("price"))==null || rs_BookDetail.wasNull())?"":rs_BookDetail_price)%>
    //this link is to THIS PAGE to send data to server as request parameters in Key/Value pairs
    // this facilitates the add to basket function
    <a href="<%= response.encodeURL(bookDetail.jsp?title=
    "+rs_BookDetail_bookTitle+"
    &item_id=
    "+rs_BookDetail_bookRef +"
    &author="+rs_BookDetail_author +"
    &price=
    "+rs_BookDetail_price) %> ">
    <img src="images\addtobasket.gif" border="0" alt="Add To Basket"></a></td>
    // use a bean instance to store basket items
    <jsp:useBean id="basket" class="ShoppingCart" scope="session"/>
    <% String title = request.getParameter("title");
    if(title!=null)
    String item_id = request.getParameter("item_id");
    double price = Double.parseDouble(request.getParameter("price"));
    Book item = new Book(item_id, title, author, price);
    basket.addToBasket( item );
    %>
    ShoppingCart class that is used as a bean in bookDetail.jsp shown above
    package com.shopengine;
    //import packages
    import java.util.*;
    //does not declare explicit constructor which automatically creates a zero argument constructor
    //as this class will be instantiated as a bean
    public class ShoppingCart
    //using private instance variables as per JavaBean api
         private Vector basket;
         public ShoppingCart()
              basket = new Vector();
         }//close constructor
    //add object to vector
         public void addToBasket (Book book)
              basket.addElement(book);
         }//close addToBasket method
    //if strings are equal, delete object from vector
         public void deleteFromBasket (String foo)
    for(Enumeration enum = getBasketContents();
    enum.hasMoreElements();)
    //enumerate elements in vector
    Book item = (Book)enum.nextElement();
    //if BookRef is equal to Ref of item for deletion
    //then delete object from vector.
    if (item.getBookRef().equals(foo))
    basket.removeElement(item);
    break;
    }//close if statement
    }//close for loop
         }//close deleteFromBasket method
    //overwrite vector with new empty vector for next customer
         public void emptyBasket()
    basket = new Vector();
         }//close emptyBasket method
         //return size of vector to show how many items it contains
    public int getSizeOfBasket()
    return basket.size();
         }//close getSizeOfBasket method
    //return objects stored in Vector
         public Enumeration getBasketContents()
    return basket.elements();
         }//close getBasketContents method
         public double getTotalPrice()
    //collect book objects using getBasketContents method
    Enumeration enum = getBasketContents();
    //instantiate variable to accrue billng total for each enummeration
    double totalBillAmount;
    //instantiate object to store data for each enummeration
    Book item;
    //create a loop to add up the total cost of items in basket
    for (totalBillAmount=0.0D; enum.hasMoreElements(); totalBillAmount += item.getPrice())
    item = (Book)enum.nextElement();
    }//close for loop
    return totalBillAmount;
         }//close getTotalPrice method
    }//close shopping cart class
    Book Class that is used as an object model for items stored in basket
    package com.shopengine;
    import java.util.*;
    public class Book{
         //define variables
    private String bookRef, bookTitle, author;
         private double price;
    //define class
    public Book(String bookRef, String bookTitle, String author, double price)
    this.bookRef= bookRef;
    this.bookTitle=bookTitle;
    this.author=author;
    this.price=price;
    //create accessor methods
         public String getBookRef()
              return this.bookRef;
         public String getBookTitle()
              return this.bookTitle;
         public String getAuthor()
              return this.author;
         public double getPrice()
              return this.price;
    }//close class

    page will only reload showing 20% of the content.Im building some carts too and I had a similiar problem getting null values from the mysql database. Are you getting null values or are they just not showing up or what?
    On one of the carts I'm building I have a similiar class to yours called products that I cast onto a hashmap works alot better. Mine looks like this, maybe this is no help I don't know.......
    public class Product {
        /**An Item that is for sale.*/
          private String productID = "Missing";
          private String categoryID = "Missing";
          private String modelNumber = "Missing";
          private String modelName = "Missing";
          private String productImage = "Missing";
          private double unitCost;
          private String description = "Missing";
          public Product( 
                           String productID,
                           String categoryID,
                           String modelNumber,
                           String modelName,
                           String productImage,
                           double unitCost,
                           String description) {
                           setProductID(productID);
                           setCategoryID(categoryID);
                           setModelNumber(modelNumber);
                           setModelName(modelName);
                           setProductImage(productImage);
                           setUnitCost(unitCost);
                           setDescription(description);        
          public String getProductID(){
             return(productID);
          private void setProductID(String productID){
             this.productID = productID;
          public String getCategoryID(){
             return(categoryID);
          private void setCategoryID(String categoryID){
             this.categoryID = categoryID;
          public String getModelNumber(){
             return(modelNumber);
          private void setModelNumber(String modelNumber){
             this.modelNumber = modelNumber;
          public String getModelName(){
             return(modelName);
          private void setModelName(String modelName){
             this.modelName = modelName;
          public String getProductImage(){
             return(productImage);
          private void setProductImage(String productImage){
             this.productImage = productImage;
          public double getUnitCost(){
              return(unitCost);
          private void setUnitCost(double unitCost){
              this.unitCost = unitCost;
          public String getDescription(){
              return(description);
          private void setDescription(String description){
              this.description = description;

  • List vs. ArrayList returns...

    Hi Java Gurus,
    Can someone tell me why its better to use List as a return type rather than using ArrayList when returning an ArrayList? I read in another forum that this is the case but didn't quite understand why.
    - Leon

    Definitely--return the List if possible. And return Map instead of HashMap. We just had a real-life issue with this at my work--if the original coders had used Map, my recent change would have been much easier to implement. I changed something that returned HashMap to now return Map--specifically, one generated using Collections.unmodifiableMap. They had cast things to HashMap everywhere (was a HashMap of HashMap, now is a Collections.unmodifiableMap with more Collections.unmodifiableMap inside), and I had to change everything to cast to Map. It was a big pain to make sure I caught all places (since I wasn't allowed to go through the whole application and just change HashMap to Map--I could only do the ones relevant to this change [or at least in the same files as ones relevant to this change]). (Never mind the fact that it shouldn't have been in any Map in the first place--it should have been real custom Objects).

  • 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

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

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

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

Maybe you are looking for

  • Please can anyone test this for me? V200 and Repeat Folder play m

    Hi Does anyone here use the play mode called Repeat Folder? I have selected this play mode and it works fine, but how do you then change/skip to another folder? If I try then the unit gets confused and goes from my folder called DireStraits of 2 to D

  • Recommended battery use

    hi, i'm trying to make sure my battery life remains as effective as possible. i've read articles that mention doing a drain once a month or so, and i've been doing that. but one thing i'm curious about is whether or not it's best to have your compute

  • Regarding table HRP1001

    Hi guys,           Need to know what is what in table hrp1001. 1) There are number of fields in this table but my interest is about OBJID and SOBID.   As far as my knowledge i assumed that this is a relationship table and defines relation between obj

  • Unwanted keyboard shortcut with dual monitors

    Problem: I have a computer setup with dual monitors (desktop extended). When I have a window open, e.g., Microsoft Word 2007, after I type "1" on the keyboard, the Word Window and mouse relocate to the second monitor. When I type "2" the Word window

  • OT: Login Form Advice

    I found a really cool registration form plugin @ http://jqueryvalidation.org/files/demo/milk/ and figured out how to connect it to a database. Then I started searching for a login form tutorial. It was kind of tricky because most tutorials are pre-PD