How to cast ArrayList to ....

Hi,
I got an ArrayList and its values are (1,2,3)
List tempList = new ArrayList();
tempList.add("1");
tempList.add("2");
tempList.add("3");
I am wondering how to convert it to an int [] array.
int [] tempInt;
I know that I can do this : tempList.toArray
but I don't know how to cast this to int[] type of array
(note: not integet [] , just int[])
Can anyone help? thanks a lot.

Note: It would be much more efficient to use the wrapper classes for storing primitives in a Vector/ArrayList/LinkedList/... :
tempList.add(new Integer(1));
tempList.add(new Integer(2));
tempList.add(new Integer(3));
(getting the array as an int[] still requires a for-loop)

Similar Messages

  • How to cast an object in JSF?

    I am working on a travel application. A user can have several bookings and a booking can have several components. A component can be either air or hotel. I want to list the user's bookings on the client using JSF datatable.
    <h:dataTable var="component" value="#{booking.components}">
    Now depending upon the class of component I need to present different information.
    My question is how to cast the variable in JSF ?
    Thanks

    You can use the String value of Object#getClass()#getName() to lookup the classname and evaluate it in the 'rendered' attribute.
    Basic example:
    package mypackage;
    public class Animal {}
    package mypackage;
    public class Cat extends Animal {}
    package mypackage;
    public class Dog extends Animal {}
    package mypackage;
    public class Fish extends Animal {}MyBeanpublic List<Animal> getList() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(new Dog());
        animals.add(new Cat());
        animals.add(new Fish());
        return animals;
    }JSF<h:dataTable value="#{myBean.list}" var="item">
        <h:column>
            <h:outputText value="It's a Cat" rendered="#{item.class.name == 'mypackage.Cat'}" />
            <h:outputText value="It's a Dog" rendered="#{item.class.name == 'mypackage.Dog'}" />
            <h:outputText value="It's a Fish" rendered="#{item.class.name == 'mypackage.Fish'}" />
        </h:column>
    </h:dataTable>As far there is no way to cast objects in JSF.
    Edit
    If you find it useful, move the classname request to the superclass:
    public class Animal {
        public String getType() {
            String className = getClass().getName();
            return className.substring(className.lastIndexOf('.') + 1);
    }Which makes life easier without struggling with package names:<h:outputText value="It's a Cat" rendered="#{item.type == 'Cat'}" />
    <h:outputText value="It's a Dog" rendered="#{item.type == 'Dog'}" />
    <h:outputText value="It's a Fish" rendered="#{item.type == 'Fish'}" />Message was edited by:
    BalusC

  • How to cast an Object into a specific type (Integer/String) at runtime

    Problem:
    How to cast an Object into a specific type (Integer/String) at runtime, where type is not known at compile time.
    Example:
    public class TestCode {
         public static Object func1()
    Integer i = new Integer(10); //or String str = new String("abc");
    Object temp= i; //or Object temp= str;
    return temp;
         public static void func2(Integer param1)
              //Performing some stuff
         public static void main(String args[])
         Object obj = func1();
    //cast obj into Integer at run time
         func2(Integer);
    Description:
    In example, func1() will be called first which will return an object. Returned object refer to an Integer object or an String object. Now at run time, I want to cast this object to the class its referring to (Integer or String).
    For e.g., if returned object is referring to Integer then cast that object into Integer and call func2() by passing Integer object.

    GDS123 wrote:
    Problem:
    How to cast an Object into a specific type (Integer/String) at runtime, where type is not known at compile time.
    There is only one way to have an object of an unknown type at compile time. That is to create the object's class at runtime using a classloader. Typically a URLClassloader.
    Look into
    Class.ForName(String)

  • How to cast vector to vector with out using loop. and how to override "operator =" of vector for this kind of condition.

    Hi All How to TypeCast in vector<>...  typedef  struct ...  to class... 
    //how to cast the vector to vector cast with out using loop
    // is there any way?
    //================ This is Type Definition for the class of ClsMytype=====================
    typedef struct tagClsMytype
    CString m_Name;
    int m_Index;
    double m_Value;
    } xClsMytype;
    //================ End of Type Definition for the class of ClsMytype=====================
    class ClsMytype : public CObject
    public:
    ClsMytype(); // Constructor
    virtual ~ClsMytype(); // Distructor
    ClsMytype(const ClsMytype &e);//Copy Constructor
    // =========================================
    DECLARE_SERIAL(ClsMytype)
    virtual void Serialize(CArchive& ar); /// Serialize
    ClsMytype& operator=( const ClsMytype &e); //= operator for class
    xClsMytype GetType(); // return the typedef struct of an object
    ClsMytype& operator=( const xClsMytype &e);// = operator to use typedef struct
    ClsMytype* operator->() { return this;};
    operator ClsMytype*() { return this; };
    //public veriable decleare
    public:
    CString m_Name;
    int m_Index;
    double m_Value;
    typedef struct tagClsMyTypeCollection
    vector <xClsMytype> m_t_Col;
    } xClsMyTypeCollection;
    class ClsMyTypeCollection : public CObject
    public:
    ClsMyTypeCollection(); // Constructor
    virtual ~ClsMyTypeCollection(); // Distructor
    ClsMyTypeCollection(const ClsMyTypeCollection &e);//Copy Constructor
    DECLARE_SERIAL(ClsMyTypeCollection)
    virtual void Serialize(CArchive& ar);
    xClsMyTypeCollection GetType();
    ClsMyTypeCollection& operator=( const xClsMyTypeCollection &e);
    ClsMyTypeCollection& operator=( const ClsMyTypeCollection &e); //= operator for class
    void Init(); // init all object
    CString ToString(); // to convert value to string for the display or message proposed
    ClsMyTypeCollection* operator->() { return this;}; // operator pointer to ->
    operator ClsMyTypeCollection*() {return this;};
    public:
    vector <ClsMytype> m_t_Col;
    //private veriable decleare
    private:
    //===================================================
    ClsMytype& ClsMytype::operator=( const xClsMytype &e )
    this->m_Name= e.m_Name;
    this->m_Index= e.m_Index;
    this->m_Value= e.m_Value;
    return (*this);
    //==========================Problem for the vector to vector cast
    ClsMyTypeCollection& ClsMyTypeCollection::operator=( const xClsMyTypeCollection &e )
    this->m_t_Col= (vector<ClsMytype>)e.m_t_Col; // how to cast
    return (*this);
    Thanks in Advance

    Hi Smirt
    You could do:
    ClsMyTypeCollection* operator->() {
    returnthis;};
    // operator pointer to ->
    operatorClsMyTypeCollection*()
    {returnthis;};
    public:
    vector<ClsMytype>
    m_t_Col;//??
    The last line with "vector<xClsMytype>
    m_t_Col;". It compiles but I doubt that is what you want.
    Regards
    Chong

  • HOW TO  CAST NVARCHAR2 TO BLOB

    Hello
    i must stock my data to a nvarchar2 data (unicode) and i must also make full text search on this column, oracle does not support full text search on unicode data, so i have decided to stock my unicode data to a blob clomun, after i can create a full text index and search data.
    my problem is how to cast nvarchar2 to blob in oracle. i'm using a vb program with adodb to write and read data from the db and i must write the data (unicode text) in the blob column using the right cast which allows me to use directly adodb to read information (i have tried this with sql server with a varbinary(max) column and it works : i write a nvarchar data to the verbinary(max) column using the cast function, after, adodb can read directly the information without any explicit cast) is this possible on oracle
    thank you for your help

    What is your database character set? If it's AL32UTF8 you shouldn't really need to use NVARCHAR2 at all - you can store Unicode data in a VARCHAR2 or CLOB column.
    BLOB doesn't seem like the right datatype to use - if it's text you want to index then it should be in a VARCHAR2 or a CLOB column. If you put it in a BLOB then you'll have to explicity tell Oracle not to treat it as a binary document, and you will have to handle all character set issues manually.
    I'm afraid I know nothing about VB or ADODB.

  • How to cast object type to integer type?

    Hi,
    Object [] temp;
    Int [] value;
    How can I assign temp to value? (value = temp?)
    In other words how to cast array of type object to array of type integer?
    Thanks a lot.

    Hi,
    Object [] temp;
    Int [] value;
    How can I assign temp to value? (value = temp?)
    In other words how to cast array of type object to
    array of type integer?
    Thanks a lot.That my friend, is (sometimes) illegal. other times use
    value = (Integer[]) temp;
    Pray that temp is holding an Integer array so that you dont throw a runtime exception.
    I am assuming you know the diff between "int" and "Integer".

  • How to cast presentation variable

    Hi,
    How to cast the presentation variable in answers
    Thanks in advance
    naresh

    Hi Naresh,
    Have you tried to use the CAST function?
    CAST(@{test}{123} as char)
    With the above column Formula in Answers Request I can able to view the result 123, which is the default value specified the presentation variable 'test'.
    Hope this will helps you..
    -Vency

  • How to cast a BLOB to OrdImage

    Hi,
    How can I cast or convert a BLOB to OrdImage? For example,
    <import...>
    public class ConvertBlobToOrdImage {
    public static void main(String args[]) throws Exception {
    // Load the Oracle JDBC driver:
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    // Connect to the database:
    Connection conn =
    DriverManager.getConnection(<"Your database connection">);
    conn.setAutoCommit(false);
    // Create a Statement:
    Statement stmt = conn.createStatement();
    String query = "SELECT blob FROM image_t where image_id = 1";
    OracleResultSet rset = (OracleResultSet) stmt.executeQuery(query);
    rset.next();
    OrdImage imageProxy = (OrdImage) rset.getCustomDatum(1, OrdImage.getFactory()); // <-- java.lang.ClassCastException: oracle.sql.BLOB
    rset.close();
    int height = imageProxy.getHeight();
    int width = imageProxy.getWidth();
    System.out.println("Image Dimension: " + height + " x " + width);
    System.out.println("Image Mime Type: " + imageProxy.getMimeType());
    TIA,
    Henry

    xwindy wrote:
    Does anyone knows how to cast a HashMap to HashMap<String, Object>?
    the session.getAttribute return only a HashMapthere is no way to do this safely
    you can use this annotation to suppress unchecked warnings
    @SuppressWarnings("unchecked")

  • How to use ArrayList?

    i'm not quite sure how to use ArrayList, i read the api documentation but it would be better if someone could explain it to me
    i have a helper method that returns a random number within a given range that picks an index at random but it won't work, here is my code:
         public String getIndex ()
              a1.get(getRandomIndex(int));
         private static int getRandomIndex (int range)
              return ((int) (Math.random () * range));
         }

    You are calling he method incorrectly. You do not use the variable type declaration when calling a method. Do this
    import java.util.*;
    public class TestClass{
         ArrayList<String> words = new ArrayList<String>();
         Random rand = new Random();
         public TestClass(){
              words.add("hello");
              words.add("world");
         public String randomSelection(){
              int index = rand.nextInt(words.size());
              return words.get(index); //notice that I am calling the method with a variable that is an integer, but I don't use "int" when I call it
         public static void main(String args[]) {
              TestClass myTest = new TestClass();
              for(int i=0;i<30;i++){
                   System.out.println(myTest.randomSelection());
    }The API documentation will list the variable type but that is only for you information. It is there so that you know what type of variable top use when calling a particular method.

  • How to convert arraylist into array

    how to convert arraylist into array?

    If you are using generics, I would use this version of toArray:
    List < X > list = ...
    X[] array = list.toArray(new X[list.size()]);If you are not using generics, that same thing looks like:
    List  list = ...
    X[] array = (X[]) list.toArray(new X[list.size()]);

  • Hql how to cast number to varchar2

    Hello.
    How to cast number to varchar2(to string)? I'm using hql toplink implementation and (don't know why) functions like cast(... as ...), to_char(...) and str(...) don't work. Please help me.
    Kuba :).
    Edited by: 854998 on 2011-04-27 03:12

    Hello Chris.
    First of all I'd like to thank you for answer. :)
    1)I can't use native query.
    2)What do you mean?
    3)I can't upgrade.
    I have something like this(it's only simple example, I have more complex query):
    getManager().createQuery("SELECT obj FROM " + EntityClass.class.getSimpleName() + " obj "
                        + " WHERE '14' = obj.number").getResultList();
    r.number is Number in Oracle and Long in entity class.
    I want to cast obj.number to String.
    Here: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-expressions expressions like cast is valid.
    So, where's the problem? My toplink version is too old?
    Thanks a lot
    Kuba.

  • How to cast a String input into Date variable?

    I am using JOptionPane.showInputDialog to ask user for a date input. This will be read in as a String. I need to pass it to a variable call date. And when I print date using JOptionPane, it should be shown as whatever the user keyed in in this format: 25/2/09. How do I do it?

    By the way, that's not casting. Casting is when you have a variable whose type is at a particular level of detail, and you assign it a different level of detail -- say, casting an int to a long, or a List to an ArrayList.
    What you want to do is convert one type to a completely different one. In particular, you're going to do that by using SimpleDateFormat to parse the String -- that is, SimpleDateFormat will read the string, pick out the individual parts that express the date, and create a Date object that corresponds to it.

  • How to cast back and use a retrieved Session Bean reference in a servlet?

    Please help!
    1. I invoke a Session Bean from a servlet :
    travelagent = home.create();
    2. I store the travelagent reference in the HTTP Session :
    session.setAttribute( "travelagent" , travelagent );------------------------------------------------------------------------------------------------------------------
    Now, in another servlet, I have to retrieve the reference to the EJB from the HTTPSession.
    I then have to use this reference to call a business method in the EJB Session Bean.
    I have tried two ways to retrieve the reference and cast it before calling the business method. I get errors in both forms of casting.
    The Values you will see below in the code:
    EJB Remote Interface : TravelAgent (TravelAgent.java)
    Business Method : listItineraries( )
    Servlet which calls the above method : ListItinerary.java
    Line 46 of ListItinerary.java : ArrayList itineraries = traveler.listItineraries();------------------------------------------------------------------------------------------------------------------
    The two ways along with the error I get on the servlet page in the browser are :
    (A)
    TravelAgent traveler = (TravelAgent)session.getAttribute("travelagent");The error I get is :
    java.rmi.NoSuchObjectException: CORBA OBJECT_NOT_EXIST 9998 Maybe; nested exception is:
         org.omg.CORBA.OBJECT_NOT_EXIST: vmcid: 0x2000 minor code: 1806 completed: Maybe
    com.sun.corba.ee.impl.javax.rmi.CORBA.Util.mapSystemException(Util.java:208)
         com.sun.corba.ee.impl.javax.rmi.CORBA.Util.wrapException(Util.java:591)
         javax.rmi.CORBA.Util.wrapException(Util.java:277)
         source.traveler.ejb._TravelAgent_Stub.listItineraries(Unknown Source)
         source.traveler.servlet.ListItinerary.processRequest(ListItinerary.java:46)
    (B)
    TravelAgent traveler  =
    (TravelAgent)PortableRemoteObject.narrow(session.getAttribute("travelagent"), TravelAgent.class);The error I get is :
    java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
         java.rmi.RemoteException
         com.sun.corba.ee.impl.javax.rmi.CORBA.Util.wrapException(Util.java:597)
         javax.rmi.CORBA.Util.wrapException(Util.java:277)
         source.traveler.ejb._TravelAgent_Stub.listItineraries(Unknown Source)
         source.traveler.servlet.ListItinerary.processRequest(ListItinerary.java:46)
    Could someone advice on how to retrieve and cast the EJBObject's reference from the servlet so that I may use it to call the business method?
    Thanks!

    Thanks guys! It worked.
    1.. I should have used the handle. Got to coding without going deep in the concepts.
    2.. I dont know if I could have used the EJB Reference directly (instead of the handle).
    3.. The error was due to me not mapping the servlets with the EJBs that they could use. I continued to get the same error even after using the handle. Once I put the mapping to the EJBs correctly, everything fell in place.
    Thanks a lot!
    Henry

  • How to cast a column of a derived column in a view to NULL

    I have a derived column in my view and this column by default is picked up as not null.
    I want to cast it to null how can i do it ?
    Actual column
    column1 varchar(3) not null
    Expected column
    column1 varchar(3)  null
    Mudassar

    Shridar I  havent defined it but the derived column has been picked up as not null which is strange
    CREATE VIEW test
    AS
    SELECT 
    CASE
    WHEN COMPANY_SIZE IS NULL then  'a'
    ELSE 'b' 
    END AS
    column1 ----- added derived column identifier
    ,[Company_Size] AS [CompanySize]
    FROM xyz
    Mudassar

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

Maybe you are looking for

  • HP Pavilion p7-1410 & Windows 7 drivers... do they exist?

    Client just bought a HP Pavilion p7-1410 (Windows 8 pre-installed). Their sole booking engine they employ currently only operates through Internet Explorer 8, which is not supported by Windows 8. This is something they have no control over, as the co

  • Windows 8.1 error on Shutdown

    Hi, I get the "explorer.exe - Application error" message whenever I shutdown my laptop. The full message is: "The instruction at 0x7e5a3cd9 referenced memory at 0x00000000. The memory could not be read. Click on OK to terminate the program." I've alr

  • [GeForceFX] Red lines on my GeForce FX 9950 Ultra

    I have recently upgraded my Graphics card from a GeForce FX 5200 to a GeForce FX 9950 Ultra. I have had no problems with the 5200 model, but when i installed the 9950 card (which is HUGE!!!) the Loading up bios screen had red vertical lines all over

  • In monitor I didnt see the receiver

    Hello Friends, Regarding the Enhanced Receiver determination. I am working on the below blog "Illustration of Enhanced Receiver Determination - SP16 I have done the design in IR as below 1) Created two data types (one input,one output) 2)Created resp

  • Why are LR3.3 and ext hdd not communicating?

    I store all my images on an ext hdd which is synched with LR on my MacBook Pro. A couple of days ago, everything was fine. Just started up ext hdd and opened LR, to be told to 'Click the import button to begin'. Everything in LR is a blank; no recogn