ClassCastException Vector

Hi,
I'm trying to initialise 2 variables to hold the values of two vectors in order for me to compare them at each position in the vectors. I'm getting the error Class cast exception.
The elements in the vLargest vector are floats but the elements in VCurInner are ints, i know this is the problem but how do i get past this?
for( ivc=0; ivc<count;ivc ++)
                    currentElement = (Float)vCurInner.elementAt(ivc);
                    currentLargest = (Float)vLargest.elementAt(ivc);
                    //do calculations
               }What i ultimately want to do is compare currentElement with currentLargest and if its bigger, place currentElement in vLargest at position ivc.
Can i do this if currentElement is an Int and currentLargest is a Float?
Can anybody help please?
Cheers

Hi,
I'm trying to initialise 2 variables to hold the
values of two vectors in order for me to compare them
at each position in the vectors. I'm getting the
error Class cast exception.So you're casting a reference into something that doesn't match. Your example shows two casts to Float. You say one's an Integer.
The elements in the vLargest vector are floats but
the elements in VCurInner are ints, i know this isSee? so why do you cast both to Floats?

Similar Messages

  • [Aglet]java.lang.ClassCastException in Vector

    Hi All,
    I sometime get the ClassCastException in the Master agent when Slave return a vector as an arg to the Master agent in Aglet Programming. The code is attached.
    The exception do not always exist that make me feel confusing about the exception.
    does anyone ever got this kind of error?
    Thanks for you any help!!
    Poor Leo
    public class Slave extends Aglet implements Serializable{
         public boolean handleMessage(Message m) {
              if (m.sameKind("tell")) {
                   Vector vStore = new Vector();
                   Cart shopCart = new Cart();
                   shopCart.noOfItem =1;
                   vStore.addElement(shopCart);
                   try {
                        Message ack = new Message("ack");
                        ack.setArg("VSTORE", vStore);
                        masterproxy.sendFutureMessage(ack);
                   }catch (Exception e){}
    public class Master extends Aglet implements Serializable{
         public boolean handleMessage(Message m) {
              if (m.sameKind("ack")) {
                   Vector vStore = new Vector();
                   VStore = (Vector)m.getArg("VSTORE");     
                   //***********ClassCastException sometime occur here********
                   Cart cart = (Cart)Vstore.elementAt(0);
                   //***********ClassCastException sometime occur here********
    public class Cart implements Serializable{
         int noOfItem = 0;
    Hashtable replyInfo = new Hashtable();
    }

    hi,
    well i cant think of why an object in a Vector at one end should get transformed to something else at the other end,... but you could try the following. at the server end, after you retrieve the object
    Object obj = Vstore.elementAt(0);        print the object using
    System.out.println("obj is :" + obj); this will print a object reference, but you will be able to figure out what the object represents..
    My guess is that somehow u are adding something else also to the Vector (maybe a null value is getting put into the vector).. check the value present in the Vector just before sending it to the Server.. log it in some file
    hope that helps
    cheerz
    ynkrish

  • ClassCastException: java.util.Vector

    I'm trying to get a list of records(products) from the dataBase and print them into a jsp page.
    Here is the code-
    Method in session bean to get the records-
    public List<Entity.Products> getProducts(int categoryId)
          Query query=manager.createNativeQuery("select * from products  where categoryId="+categoryId);
          return (List<Entity.Products>)query.getResultList();
        }I put the result in the request (in a servlet)-
       request.setAttribute("products",productsManagement.getProducts(categoryId));JSP page-
          <%
             java.util.List<Entity.Products> products=(java.util.List<Entity.Products>) request.getAttribute("products");
              for(Entity.Products product : products)
               %>
            <A href=""><%=product.getProductName()%></A>
               <%
               %>The problen is that i'm getting the error-
    java.lang.ClassCastException: java.util.Vector
    what is the problem?
    Thanks in advanced.

    ppl1,
    Your problem is with createNativeQuery. Native query returns a Vector of objects. Whereas createNamedQuery (based on JPQL) is smart enough to get the types right. It seems like you want to use createNamedQuery which will allow you to use generics with the Entity type.
    For example, with a client
    List<Products> products = prodMgr.findAllProducts();
    for(Product p : products) {
    System.out.println(p");
    }The following session bean will work.
    // ProdManager
    @PersistenceContext EntityManager em;
    public List<Product> findAllProducts() {
      // JPQL for findAllDepts: SELECT p FROM Product AS p
      return em.createNamedQuery("findAllDepts");
    }If you are committed to native query, use the following on the client and EJB respectively.
    List products = prodMgr.findAllProducts();
    for( Object obj : products ) {
      System.out.println( obj.toString());
      // use a case "(Product)obj" for field-level access
    List findAllProducts() {
    return em.createNativeQuery("SELECT * FROM products").getResultList();
    }

  • ClassCastException for Vector

    Hi,
    While the following first exmpl. runs, for the second one I get ClassCastException, why?
    1)
    pList=getHashtable(); // getHashtable() returns hashTable;
    MyClass obj=(MyClass)pList.get(key);
    2)
    pList= getEntries(); // getEntries() returns new Vector(hashTable.entrySet())
    MyClass obj=(MyClass)pList.firstElement();

    I think it is because of the entrySet method:
    the API says:
    entrySet
    public Set entrySet()Returns a set view of the mappings contained in this map. Each element in the returned set is a Map.Entry. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress, the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
    Returns:
    a set view of the mappings contained in this map.
    So basically, the elements in your Vector will not be of type MyClass. I guess you'll have to think of another way to populate your Vector, like using the elements method of Hashtable, and then looping the Enumeration and put the elements one by one into your Vector.

  • Error while retriving the values from a vector in jsp

    Vector AppDetails is set in a Attribute of request scope as.
    Vector[] AppDetails = (Vector[])port.retrieveAppDetails(appID);
    request.setAttribute("AppDetails",AppDetails);
    But while retriving the same in the jsp by
    Vector AppDetails =(Vector)request.getAttribute("AppDetails");
    its giving an error as
    java.lang.ClassCastException: [Ljava.util.Vector;
    so i am trying with this code now
    Object attr = request.getAttribute("AppDetails");
    if(attr instanceof Vector)
         System.out.println("is instance of vector");
    }     else
    System.out.println("is not a instance");
    System.out.println("I'm seeing a " + attr.getClass().getName());
    here the output is 'is not a instance'. Suggest me on the same.

    You are setting the array of vector in request object, but you are trying get the object as normal vector object. that's why are you getting error. try to get the vector object as array of vector.

  • ClassCastException in method declaration in JSP page??

    i keep getting this ClassCastException in my jsp page. The line that
    is apparently the problem is the <%! where the method declaration
    starts. I can't seem to figure out why this is happening, can someone
    please help? Here is the full code:
    java.lang.ClassCastException
         at quickfix0itm_0submit__jsp.addUpdate(/epsc/quickfix_itm_submit.jsp:25)
         at quickfix0itm_0submit__jsp._jspService(/epsc/quickfix_itm_submit.jsp:165)
         at com.caucho.jsp.JavaPage.service(JavaPage.java:75)
         at com.caucho.jsp.Page.subservice(Page.java:506)
         at com.caucho.server.http.FilterChainPage.doFilter(FilterChainPage.java:182)
         at com.caucho.server.http.Invocation.service(Invocation.java:315)
         at com.caucho.server.http.CacheInvocation.service(CacheInvocation.java:135)
         at com.caucho.server.http.RunnerRequest.handleRequest(RunnerRequest.java:344)
         at com.caucho.server.http.RunnerRequest.handleConnection(RunnerRequest.java:274)
         at com.caucho.server.TcpConnection.run(TcpConnection.java:139)
         at java.lang.Thread.run(Thread.java:534)
    <%
    if ( (session.getAttribute("setID") == null ) || ( !session.getAttribute("setID").equals(session.getId()) ))
            out.write("You are either not logged in or your session has timed out due to inactivity.<BR>"
                    + "Please <a href=\"index.jsp\">return to the login screen</a> and login again<BR><BR>");
    else
    %>
    <%@ page language=java %>
    <%@ page import='java.sql.*' %>
    <%@ page import='javax.sql.*' %>
    <%@ page import='javax.naming.*' %>
    <%@ page import='java.io.*' %>
    <%@ page import='java.util.Hashtable' %>
    <%@ page import='java.util.Vector' %>
    <%@ page import='java.util.Enumeration' %>
    <%@ page import='java.util.Calendar' %>
    <%@ page import='java.util.GregorianCalendar' %>
    <%!
    private void addUpdate(String[] tmpP, String[] UIDs, String curName, String colName, String lastIdx, Hashtable uid_updates)
         if (curName.equals(colName))
              for (int c = 0; c < UIDs.length; c++)
                   Object[] tmp = (Object[])uid_updates.get(UIDs[c]);
                   Vector colNames = new Vector();
                   Vector colValues = new Vector();
                   if (tmp == null)
                        tmp = new Object[2];
                   else
                        colNames = (Vector)tmp[0];
                        colValues = (Vector)tmp[1];
                   String updateVal = tmpP[0];
                   colNames.add(curName);
                   colValues.add(updateVal);
                   tmp[0] = colNames;
                   tmp[1] = colValues;
                   uid_updates.remove(UIDs[c]);
                   uid_updates.put(UIDs[c], tmp);
         else
              int uidIdx = curName.lastIndexOf(lastIdx);
              String uidcode = curName.substring(uidIdx + 1);
              Object[] tmp = (Object[])uid_updates.get(uidcode);
              Vector colNames = new Vector();
              Vector colValues = new Vector();
              if (tmp == null)
                   tmp = new Object[2];
              else
                   colNames = (Vector)tmp[0];
                   colValues = (Vector)tmp[1];
              //String[] tmpP = request.getParameterValues(curName);
              String updateVal = tmpP[0];
              colNames.add(colName);
              colValues.add(updateVal);
              tmp[0] = colNames;
              tmp[1] = colValues;
              uid_updates.remove(uidcode);
              uid_updates.put(uidcode, tmp);
    %>
    <%
    String ss = "0";
    String force_noon = "0";
    String qfix_duration = "2";
    int qfixd = 2;
    String mod_keys = "";
    String[] mktmp = request.getParameterValues("mod_keys");
    if (mktmp == null)
         out.print("Error! Please go back and try again.");
    else
         mod_keys = mktmp[0];
    Hashtable uid_updates = new Hashtable();
    String[] UIDs = new String[1];
    if (mod_keys.equals("1"))
         UIDs = request.getParameterValues("UID");
         for (int storeUIDs = 0; storeUIDs < UIDs.length; storeUIDs++)
              Vector tmp = new Vector();
              uid_updates.put(UIDs[storeUIDs], tmp);
    Enumeration cols = request.getParameterNames();
    while (cols.hasMoreElements())
         String curName = (String)cols.nextElement();
         if (curName.indexOf("BusName") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "BusName", "e", uid_updates);
         else if (curName.equals("ss"))
              String[] asdfadf  = request.getParameterValues(curName);
              if (asdfadf != null)
                   ss = "1";
              else
                   ss = "0";
         else if (curName.equals("force_noon"))
              String[] asdfadf  = request.getParameterValues(curName);
              force_noon = asdfadf[0];
         else if (curName.equals("qfix_duration"))
              String[] asdfadf  = request.getParameterValues(curName);
              qfix_duration = asdfadf[0];
              qfixd = Integer.parseInt(qfix_duration);
         else if (curName.indexOf("DisplayLine") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "DisplayLine", "e", uid_updates);
         else if (curName.indexOf("CityName") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "CityName", "e", uid_updates);
         else if (curName.indexOf("PAC") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "PAC", "C", uid_updates);
         else if (curName.indexOf("ProvDisp") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "ProvDisp", "p", uid_updates);
         else if (curName.indexOf("TeleNum") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "TeleNum", "m", uid_updates);
         else if (curName.indexOf("ProvCode") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "ProvCode", "e", uid_updates);
         else if (curName.indexOf("Dircode") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "Dircode", "e", uid_updates);
         else if (curName.indexOf("Hdgcode") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "Hdgcode", "e", uid_updates);
         else if (curName.indexOf("EMail") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "EMail", "l", uid_updates);
         else if (curName.indexOf("URL") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "URL", "L", uid_updates);
         else if (curName.indexOf("DispAd") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "DispAd", "d", uid_updates);
         else if (curName.indexOf("TOPlus") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "TOPlus", "s", uid_updates);
         else if (curName.indexOf("EStore") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "EStore", "e", uid_updates);
         else if (curName.indexOf("HSLINE_EN") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "HSLINE_EN", "N", uid_updates);
         else if (curName.indexOf("HSLINE_FR") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "HSLINE_FR", "R", uid_updates);
         else if (curName.indexOf("MtlPlus") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "MtlPlus", "s", uid_updates);
         else if (curName.indexOf("CalPlus") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "CalPlus", "s", uid_updates);
         else if (curName.indexOf("EdmPlus") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "EdmPlus", "s", uid_updates);
         else if (curName.indexOf("VanPlus") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "VanPlus", "s", uid_updates);
         else if (curName.indexOf("DEALER_LOCATOR") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "DEALER_LOCATOR", "R", uid_updates);
    long curTime = System.currentTimeMillis();
    long monthMS = 2629743832L;
    long expLength = monthMS * qfixd;
    long expTime = curTime + expLength;
    java.sql.Date d1 = new java.sql.Date(System.currentTimeMillis());
    String Start_Date = d1.toString();
    d1 = new java.sql.Date(expTime);
    String Expiry_Date = d1.toString();
    Context env1 = (Context) new InitialContext().lookup("java:comp/env");
    DataSource source1 = (DataSource) env1.lookup("jdbc/epsc");
    Connection conn1 = source1.getConnection();
    String Pub_ID = "";
    try {
         Enumeration uidKeys = uid_updates.keys();
         while (uidKeys.hasMoreElements())
              String Unique_ID = (String)uidKeys.nextElement();
              Object[] updateData = (Object[])uid_updates.get(Unique_ID);
              Vector colNames = (Vector)updateData[0];
              Vector colValues = (Vector)updateData[1];
              String selectRecord = "SELECT * from epsc_ypca WHERE Unique_ID='" + Unique_ID + "';";
              Statement getRecord = conn1.createStatement();
              ResultSet returned = getRecord.executeQuery(selectRecord);
              Pub_ID = returned.getString("Pub_ID");
              boolean createDelete = false;
              String updateString = "";
              for (int b = 0; b < colNames.size(); b++)
                   if (b != 0)
                        updateString = updateString + ", ";
                   String colName = (String)colNames.get(b);
                   String colVals = (String)colValues.get(b);
                   if (colName.equals("BusName") || colName.equals("DisplayLine") || colName.equals("ProvDisp") || colName.equals("CityName") || colName.equals("PAC") || colName.equals("TeleNum"))
                        if (!((returned.getString(colName)).equals(colVals)))
                             createDelete = true;
                   updateString = updateString + colName + "='" + colVals + "'";
              if (createDelete)
                   //create delete
                   String delFromQuickfixes = "DELETE FROM epsc_quickfixes WHERE Start_Date='" + Start_Date + "' AND Pub_ID='" + Pub_ID + "' AND QFix_Type='2';";
                   Statement delItm = conn1.createStatement();
                   delItm.execute(delFromQuickfixes);
                   String insertQfixDel = "INSERT INTO epsc_quickfixes SELECT *, '0' as UID, '" + Start_Date + "' as Start_Date, '" + Expiry_Date + "' as Expiry_Date, '2' as QFix_Type, '0' as ss, '" + force_noon + "' as force_noon FROM epsc_ypca WHERE Pub_ID='" + Pub_ID + "' AND (Record_Ind='2' OR Record_Ind='4' OR Record_Ind='6');";
                   Statement insertQFDEL = conn1.createStatement();
                   insertQFDEL.execute(insertQfixDel);
              String updateRecords = "UPDATE epsc_ypca SET " + updateString + " WHERE Unique_ID='" + Unique_ID + "';";
         String selectAndInsert = "INSERT INTO epsc_quickfixes SELECT *, '0' as UID, '" + Start_Date + "' as Start_Date, '" + Expiry_Date + "' as Expiry_Date, '3' as QFix_Type, '" + ss + "' as ss, '" + force_noon + "' as force_noon FROM epsc_ypca WHERE Pub_ID='" + Pub_ID + "';";
         Statement insertIntoQfix = conn1.createStatement();
         insertIntoQfix.execute(selectAndInsert);
         out.write("Quickfix Successfully submitted.<BR><BR>\r\n");
    catch (SQLException e)
            out.write("<h1>SQL ERROR: " + e.getMessage() + "<BR><BR>Please report to administrator</h1>");
    finally{
            conn1.close();
    %>
    <BR><BR>[ <a href="menu.jsp">Return To Main</a> ]
    </center>
    </BODY>
    </HTML>
    <%
    %>

    it is the exact same as the one i originally posted:
    500 Servlet Exception
    java.lang.ClassCastException
         at quickfix0itm_0submit__jsp.addUpdate(/epsc/quickfix_itm_submit.jsp:24)
         at quickfix0itm_0submit__jsp._jspService(/epsc/quickfix_itm_submit.jsp:169)
         at com.caucho.jsp.JavaPage.service(JavaPage.java:75)
         at com.caucho.jsp.Page.subservice(Page.java:506)
         at com.caucho.server.http.FilterChainPage.doFilter(FilterChainPage.java:182)
         at com.caucho.server.http.Invocation.service(Invocation.java:315)
         at com.caucho.server.http.CacheInvocation.service(CacheInvocation.java:135)
         at com.caucho.server.http.RunnerRequest.handleRequest(RunnerRequest.java:344)
         at com.caucho.server.http.RunnerRequest.handleConnection(RunnerRequest.java:274)
         at com.caucho.server.TcpConnection.run(TcpConnection.java:139)
         at java.lang.Thread.run(Thread.java:534)

  • Java.lang.ClassCastException in JSP page

    My JSP page:
    <%@page contentType="text/html"%>
    <HTML>
    <HEAD>
    <TITLE> JDBC Servlet/JSP Example </TITLE>
    </HEAD>
    <BODY>
    <%@ page import="myBeans.memoryBean" %>
    <%@ page import="java.util.Vector" %>
    <H1> JDBC Servlet/JSP Example </H1>
    <H2> <%= session.getValue("message") %>
    </H2>
    <UL>
    <%
         Vector vData = (Vector) session.getValue("res");
         myBeans.memoryBean mb;
         Object o;
         for (Enumeration e = vData.elements() ; e.hasMoreElements() ;) {
              o = e.nextElement();
              mb = (myBeans.memoryBean) o;
    %>
        <LI> <%= o.getClass().getName() %>
    <%      } // end for
    %>
    </UL>
    </BODY>
    </HTML>Notice that I don't even use the object I cast but I still get the error message:
    Exception:
    java.lang.ClassCastException
         at _memory._search._jspService(_search.java:66)
         at oracle.jsp.runtime.HttpJsp.service(HttpJsp.java)
         at oracle.jsp.app.JspApplication.dispatchRequest(JspApplication.java)
         at oracle.jsp.JspServlet.doDispatch(JspServlet.java)
         at oracle.jsp.JspServlet.internalService(JspServlet.java)
         at oracle.jsp.JspServlet.service(JspServlet.java)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:588)
         at org.apache.jserv.JServConnection.processRequest(JServConnection.java:314)
         at org.apache.jserv.JServConnection.run(JServConnection.java:188)
         at java.lang.Thread.run(Thread.java:534)When I comment out the line that castes my object my browser displays:
    JDBC Servlet/JSP Example
    Records Found:
        * myBeans.memoryBean
        * myBeans.memoryBean
        * myBeans.memoryBean Notice that the three objects that are returned are exactly the type that I caste to.
    Also, I did a getClass().getClassLoader() when I create the objects in my servlet code and again on the JSP pages for each object I pull out of the vector and the class loader matched.
    I even changed the package on my bean class and recompiled everything to make sure it wasn't a old .class file floating around.
    Could this have something to do with my classpath or where my classes are being placed? I found a similar problem here: http://forum.java.sun.com/thread.jsp?forum=33&thread=380437&start=0&range=15&hilite=false&q=
    but the explanation of what was done wasn't clear
    Anyone have any idea what's going on here?
    I am using:
    Oracle 9i
    Oracle HTTP Server Powered by Apache/1.3.12 (Unix)
    ApacheJServ/1.1
    Thanks in advance.
    - Linus

    Is ti at all possible that you have another jar / zip file with the same class file in it, seemingly away from the Server classpath ? In which case this could happen even though logically it shouldn't !!!

  • How do we do TypeMapping for Vector, Hashtable, or any java data structure in RPC?

    I tried to implement a dynamic Client (RPC) however I got the following Error
    when I ran the program.
    Exception in thread "main" java.lang.ClassCastException
    Here is my part of code
    //create service
    Service service = factory.createService( serviceName );
    TypeMappingRegistry registry = service.getTypeMappingRegistry();
    TypeMapping mapping = registry.getTypeMapping(
    SOAPConstants.URI_NS_SOAP_ENCODING );
    mapping.register( Vector.class,                          
              new QName( targetNamespace, "Vector" ),      
              new language_builtins.util.VectorCodec(),                         new language_builtins.util.VectorCodec()
    //create call
    Call call = service.createCall();
    //set port and operation name
    call.setPortTypeName( portName );
    call.setOperationName( operationName );
    call.addParameter( "string",new QName( "http://www.w3.org/2001/XMLSchema","string"
    ParameterMode.IN);
    call.addParameter( "intVal",new QName( "http://www.w3.org/2001/XMLSchema","int"
    ParameterMode.IN);
    call.setReturnType( new QName( targetNamespace, "Vector" ) );
    Vector v = (Vector) call.invoke(new Object[] {"Hi", new Integer(1) });
    Any help on this will be greatly appreciated.
    december

    Hey December,
    I looked at your WSDL, but it doesn't give any hint of what you are putting in
    the LinkedList or Vector. All it says is that an "array of anything" (basically,
    an array of java.lang.Object) is returned from the buy and sell web service operations.
    Surely there is some complexType (i.e. TradeResults, TransactionResults, etc.)
    that you want to return here. A java.util.LinkedList object is not a complexType.
    It's a generic container object which is specific to the Java programming language.
    Same with the java.util.Vector. Web services are programming language independent,
    so a .NET client (written in C# or VB code) wouldn't really know how to deal with
    a java.util.LinkedList, right? Web services do not transfer objects back and forth,
    just XML. This means that the buy web service operation doesn't really return
    a java.util.Vector over an HTTP connection. It returns an XML representation of
    the "hierarchical state" associated with the complexTypes you put in the Vector,
    inside the "service implementation" code on the server side.
    What you want to do is use the WSDL "to describe" the data types your web services
    accepts and returns. To do this, you'll need to define complexTypes to put in
    the array of complex types that is returned. If you leave things as they are,
    I don't think you'll ever be able to determine what's in "the Vector". Again,
    this is because web services don't transfer objects back and forth, just the state
    that is used to instanciate them :-)
    HTH,
    Mike Wooten
    "december_i" <[email protected]> wrote:
    >
    >
    >
    Hi Michael Wooten,
    When I printed out the Object class name, it returned this "[Ljava.lang.Object;"
    So I tried this way again.
    Object[] obj = (Object[])call.invoke(new Object[] {"Hi", new Integer(1)});
    System.out.println("obj[0].getClass().getName()=" + obj[0].getClass().getName());
    At this time, it printed this "java.lang.String".
    I guess web services is not returning Vector.
    I attached my WSDL file.
    I really appreciated your help.
    best wishes,
    December
    "Michael Wooten" <[email protected]> wrote:
    If you are still getting a class cast exception, maybe it's becausethe
    web service
    isn't returning a Vector.
    Change the following line in your client code:
    Vector v = (Vector) call.invoke(new Object[] {"Hi", new Integer(1)});
    to:
    Object obj = call.invoke(new Object[] {"Hi", new Integer(1)});
    System.out.println("obj.getClass().getName()=" + obj.getClass().getName());
    That way you can see what the return type is :-)
    You might want to post the WSDL and remote interface of the web service
    you are
    trying to call also.
    Regards,
    Mike Wooten
    "december_i" <[email protected]> wrote:
    Hi Mike Wooten,
    Thanks for pointing out my mistake.
    However I'm still getting same error. I know i'm gettting this error
    because of
    return type "Vector". But I don't know what I did wrong.
    Does anybody have any sample example about TypeMapping for any datastructures?
    Any help on this will be greatly appreciated.
    December
    "Michael Wooten" <[email protected]> wrote:
    Hi December_i,
    Your code is saying that the "Vector" type is in the target namespace
    for your
    web service. I don't think this is correct. Try this:
    mapping.register(
    java.util.Vector.class,                          
    new QName("java:language_builtins.util", "Vector" ),      
    new language_builtins.util.VectorCodec(),
    new language_builtins.util.VectorCodec()
    call.setReturnType( new QName("java:language_builtins.util", "Vector"
    HTH,
    Mike Wooten
    "december_i" <[email protected]> wrote:
    I tried to implement a dynamic Client (RPC) however I got the following
    Error
    when I ran the program.
    Exception in thread "main" java.lang.ClassCastException
    Here is my part of code
    //create service
    Service service = factory.createService( serviceName );
    TypeMappingRegistry registry = service.getTypeMappingRegistry();
    TypeMapping mapping = registry.getTypeMapping(
    SOAPConstants.URI_NS_SOAP_ENCODING
    mapping.register( Vector.class,                          
              new QName( targetNamespace, "Vector" ),      
              new language_builtins.util.VectorCodec(),                         new language_builtins.util.VectorCodec()
    //create call
    Call call = service.createCall();
    //set port and operation name
    call.setPortTypeName( portName );
    call.setOperationName( operationName );
    call.addParameter( "string",new QName( "http://www.w3.org/2001/XMLSchema","string"
    ParameterMode.IN);
    call.addParameter( "intVal",new QName( "http://www.w3.org/2001/XMLSchema","int"
    ParameterMode.IN);
    call.setReturnType( new QName( targetNamespace, "Vector" ) );
    Vector v = (Vector) call.invoke(new Object[] {"Hi", new Integer(1)
    Any help on this will be greatly appreciated.
    december

  • Converting vector to string array

    How can I convert values in a vector into a string array?
    Vector formsVector = new Vector();
    while (rs.next())
    {formsVector.add(rs.getString("forms"));}
    String forms[] = (String[])formsVector.toArray();
    I tried the above line but it did not work. Any input please?
    Thanks

    .... What is the difference between the two as
    according to online help, both are same.
    String forms[] = (String [])formsVector.toArray();
    String forms[] = (String [])formsVector.toArray( new
    String[0] );The difference lies in the type of the object returned from toArray. The first form you list, formsVector.toArray(), always returns an Object[]. In your example, you'll get a ClassCastException at runtime when you cast to String[].
    The second form will try to use the array you pass in. If it's not big enough, it'll create a new one of the same type as that array. This is what's happening when passing a zero-length array into toArray.
    My personal preference is to save an extra instantiation and build the array to the proper size to begin with:String forms[] = (String [])formsVector.toArray( new String[formsVector.size()] );

  • Sort a vector of objects by one of its attributes

    Hi all!
    I have created this class:
    public class Client {
    private int numero;
    private double tempsEntrada;
    private double tempsServei;
    private double tempsIniciSessio;
    private char tipus;
    * Creates a new instance of Client
    public Client(int num, double temp,double servei, char tip) {
    numero = num;
    arrivalTime = temp;
    serviceTime = servei;
    tipus = tip;
    public char getTipus()
    return tipus;
    public int getNumero()
    return numero;
    public double getTempsEntrada()
    return arrivalTime;
    public double getTempsServei()
    return serviceTime;
    Now I've done a java vector of this object, and I want to sort it by arrivalTime.
    The class comparer looks like this
    public class Comparer implements Comparator {
    public int compare(Object obj1, Object obj2)
    double temps1 = ((Client)obj1).getTempsEntrada();
    double temps2 = ((Client)obj2).getTempsEntrada();
    return (int)(temps1 - temps2);
    now when I do Collections.sort(vector);
    this is the error reported:
    Exception in thread "main" java.lang.ClassCastException: cafevirtual.Client cannot be cast to java.lang.Comparable
    at java.util.Arrays.mergeSort(Arrays.java:1144)
    at java.util.Arrays.mergeSort(Arrays.java:1155)
    at java.util.Arrays.mergeSort(Arrays.java:1155)
    at java.util.Arrays.sort(Arrays.java:1079)
    at java.util.Collections.sort(Collections.java:117)
    at cafevirtual.Main.main(Main.java:76)
    Java Result: 1
    what's wrong?
    thanks!

    Your Client class does not implement Comparable. You have to specify the Comparator to use: Collections.sort(vector, new Comparer());

  • Sorting a vector of objects using attribute of object class as comparator

    i would like to sort a vector of objects using an attribute of object class as comparator. let me explain, i'm not sure to be clear.
    class MyObject{
    String name;
    int value1;
    int value2;
    int value3;
    i've got a Vector made of MyObject objects, and i would sort it, for instance, into ascending numerical order of the value1 attribute. Could someone help me please?
    KINSKI.

    Vector does not implement a sorted collection, so you can't use a Comparator. Why don't you use a TreeSet? Then you couldclass MyObject
      String name;
      int value1;
      int value2;
      int value3;
      // Override equals() in this class to match what our comparator does
      boolean equals (Object cand)
        // Verify comparability; this will also allow subclasses.
        if (cand !instanceof MyObject)
          throw new ClassCastException();
        return value1 = cand.value1;
      // Provide the comparator for this class. Make it static; instance not required
      static Comparator getComparator ()
        // Return this class's comparator
        return new MyClassComparator();
      // Define a comparator for this class
      private static class MyClassComparator implements Comparator
        compare (Object cand1, Object cand2)
          // Verify comparability; this will also allow subclasses.
          if ((cand1 !instanceof MyObject) || (cand2 !instanceof MyObject))
            throw new ClassCastException();
          // Compare. Less-than return -1
          if ((MyObject) cand1.value1 < (MyObject) cand2.value1))
            return -1;
          // Greater-than return 1
          else if ((MyObject) cand1.value1 > (MyObject) cand2.value1))
            return 1;
          // Equal-to return 0.
          else
            return 0;
    }then just pass MyObject.getComparator() (you don't need to create an instance) when you create the TreeSet.

  • Compare element in a vector

    hi,
    I want to compare the float no in a vector e.g. [{0.2},{0.55}];
    but I cannot just compare the 2 using x.elementAt(i) becoz this return object so
    i do ix.elementAt(i) nstanceOf float but it pops up error,
    but I am actually doing object instance of float, I am wondering where it was wrong
    for(int i=1;i<x.size(); i++){
    if(x.elementAt(i) instanceOf float){
    if( x.elementAt(i)< x.elementAt(i-1)){
    mean_dist.addElement(x.elementAt(i));
    mean_dist.toString();
    System.out.println("train data: "+ mean_dist);
    anyone can give me idea
    many thx

    yep, sure thing, when you use Vector.elementAt(index) it returns an Object, not a Float
    but... you KNOW its a Float cos thats what you put there! ok?
    Vector has to return Object as when the class was written there was no idea what you would use it for and Object is the general class that coveres just about everything..
    what you need to do is "cast" to Float, that is saying,
    "ok you dont know its a Float, but I do ( I hope) and I want you to deal with it as a Float"
    the way you do this is Float gimme=(Float)myVector.elementAt(index);this tell the compiler that you expect a Float and should deal with the return as a Float
    the compiler will do its best to use what it gets as a Float, but if it cant (ie if you put something that isnt a Float in myVector at (index)) then it will generate a ClassCastException
    you dont HAVE to catch this, but you may if you want

  • Servlet passing values to JSP and ClasscastException

    I am using weblogic 5.1 to run my Servlets.
              I want to know when I forward from a servlet to a JSP how do I pass
              values especially Java Objects (Sometimes Objects of User written Java
              classes).
              Uptil now I have been putting all values in the session from where the
              JSP picks them up, but somehow I have a feeling that this is not the
              right way.
              In a code I am putting a Java Object (It contains two attributes of
              Java.util.Vector type) in the session so that the JSP to which I am
              forwarding it to can use it I have put my class in the ServletClasses.
              Intertestingly it runs well till the contents of the Vector are changed.
              As the contents of the vector are changed, it throws ClassCastException
              The StackTrace is as follows:
              java.lang.ClassCastException
              at
              jsp_servlet._select_95_account_95_profile._jspService(_select_95_account_95_pro
              file.java, Compiled Code)
              at weblogic.servlet.jsp.JspBase.service(JspBase.java, Compiled
              Code)
              at
              weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java,
              C
              ompiled Code)
              at
              weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.j
              ava:143)
              at
              com.logistics.optistopasp.servlet.AccountSelectServlet.doPost(AccountSelectServ
              let.java, Compiled Code)
              at
              com.logistics.optistopasp.servlet.AccountSelectServlet.doGet(AccountSelectServl
              et.java:35)
              at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
              at javax.servlet.http.HttpServlet.service(HttpServlet.java:865)
              at
              weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java,
              C
              ompiled Code)
              at
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImpl.j
              ava, Compiled Code)
              at
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImpl.j
              ava, Compiled Code)
              at
              weblogic.servlet.internal.ServletContextManager.invokeServlet(ServletContextMan
              ager.java, Compiled Code)
              at
              weblogic.socket.MuxableSocketHTTP.invokeServlet(MuxableSocketHTTP.java,
              Compile
              d Code)
              at
              weblogic.socket.MuxableSocketHTTP.execute(MuxableSocketHTTP.java,
              Compiled Code
              at weblogic.kernel.ExecuteThread.run(ExecuteThread.java,
              Compiled Code)
              Can anybody please Help!!!!.
              Thanks
              Pankaj
              

    Only can confirm your finding - the jsp is using a different class loader to the servlet that originally instantiated the object. There's the rub. I haven't figured out yet how to fix that. I can get the classloader but don't know how to get the runtime to use that class loader to perform cast.
              

  • Java.lang.ClassCastException: org.apache.crimson.tree.XmlDocument

    Hi all,
    i am new to java. I am trying to parse an xml document. the code is as follows:-
    Document document = null;
    DocumentBuilderFactory factory = ocumentBuilderFactory.newInstance();
    try {
         DocumentBuilder builder = factory.newDocumentBuilder();
         document = builder.parse( new File(xmlFile) );
    after this i am trying to traverse using treewalker :-
    Element docElem = document.getDocumentElement();
                   DocumentTraversal docTrav = (DocumentTraversal) document;
                   TreeWalker treeWalk = docTrav.createTreeWalker(docElem, NodeFilter.SHOW_ELEMENT, new ConfigNodeFilter(), false);
              Node node = treeWalk.nextNode();
    when i compile all is fine but while runnig it. i get the following error:-
    java.lang.ClassCastException: org.apache.crimson.tree.XmlDocument
    at - DocumentTraversal docTrav = (DocumentTraversal) document;.
    my import statements are as follows:-
    import java.io.File;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    import java.util.Vector;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.traversal.DocumentTraversal;
    import org.w3c.dom.traversal.NodeFilter;
    import org.w3c.dom.traversal.TreeWalker;
    import org.xml.sax.SAXException;
    i am not able to understand why the error is coming.
    any help will be appreciated.

    "In DOMs which support the Traversal feature, DocumentTraversal will be implemented by the same objects that implement the Document interface. "
    My guess is that the DOM parser you are using doesn't support the DocumentTraversal interface which is why you can not cast to that class.

  • ClassCastException in JSP

    This is driving me NUTS!!
              I set up a vector object in a servlet and use it to store some javabeans. I
              then store the Vector in the application object), forward to a JSP and
              iterate thru the Vector.
              In doing so I cast the elements to the bean class. I get a
              classcastException that does not make sense. When I do
              vector.elementAt(i).getClass().getName() it has the correct class name! So
              why can't I cast to it?
              This is a show stopper for me, please help.
              John.
              

    Michael , we had the same problem.
              It came out to be due to the fact that we were putting the Beans for the
              Servlets (the Helper classes) in the servletclasses directory together with
              the servlets.
              In this way they will only be available to the servlets , but not to the
              JSPs,
              which use a different class loader..
              We solved all of this by putting thebean class in the JAVA_CLASSPATH
              and NOT in the servletclasses...
              Now everything works beautifully!
              Max
              MIchael Raisis <[email protected]> wrote in message
              news:[email protected]...
              > I am having a similar problem but only when I try and
              > pass an object from a servlet to a JSP using the request
              > object.
              >
              > If I use the session object everything is fine.
              >
              > I am using Servlet 2.2 Web applications.
              >
              > Any suggestions?
              >
              >
              > "Jas" <[email protected]> wrote in message
              > news:[email protected]...
              > > welcome to the club
              > >
              > > JOG wrote:
              > >
              > > > This is driving me NUTS!!
              > > > I set up a vector object in a servlet and use it to store some
              > javabeans. I
              > > > then store the Vector in the application object), forward to a JSP and
              > > > iterate thru the Vector.
              > > >
              > > > In doing so I cast the elements to the bean class. I get a
              > > > classcastException that does not make sense. When I do
              > > > vector.elementAt(i).getClass().getName() it has the correct class
              name!
              > So
              > > > why can't I cast to it?
              > > >
              > > > This is a show stopper for me, please help.
              > > > John.
              > >
              >
              >
              

Maybe you are looking for

  • HP LJ4mv wireless printer worked with OS 10.5.5 but not with 10.6.3 - help!

    My ancient HP worked with 10.4.11 and 10.5.1 thru 10.5.5 wirelessly. With 10.5.6 thru 10.5.8 installed, the printer did ot work and only the Adobe printer appeared in the Printer/Fax setup. With 10.5.5, I was experiencing random horizontal gray lines

  • Error(33,79): Reference ByeServiceService does not exist as wire target

    I have simple test BPEL created in Jdev 11gR1+. The BPEL has one partner link to asynch WebService (HelloService). The HelloService internally invokes ByeServiceService but the ByeServiceService is not connected to BPEL. (BPEL only communicates to He

  • A Conduit, a Palm database created with a MIDlet ... HELP!!!

    Using a MIDlet I created a database called "Customers-VM00", with creator ID "VM00", this database has two records: 1) 48476472\Luis\Bello Ortega\201398400000\ 2) 00000000\Jana\Hajkova\144288000000\ Ok, my goal is to get those two lines in my Conduit

  • CLASSIC don't works as under 10.3.9!

    I have made a new install of Mac OS 9.2.2 and 10.4.5 on two seperate partitions onto my G4 AGP Graphics("Sawtooth") with 466 MHz and HD 20 GB. After I started Classic it seems to start like every time, but at the end of the starting process nothing h

  • S/W developer is asking for proof of purchase

    Hi I purchased software through the iTunes store. I'm having trouble with it and the developer is asking for proof of purchase. I went to 'purchased', and see it, but it doesn't give any indication that I've actually purchased it. Is there a way I ca