Cast array issue?

Can Java Array Object be cast to another type? For example:
Vector<MyClass> vector = new Vector<MyClass>();
MyClass []mc = (MyClass[])vector.toArray();The last line can't worked.

SteveLam wrote:
MyClass[] mc = new MyClass[vector.size()];
vector.toArray(mc);and it can pass.Strictly speaking your last line should be this:
mc = vector.toArray(mc);While all the implementations I've seen use the array, if its of the correct size, the specification does not require that. A call toArray() can return a new array, as long as it's of the same type as the parameter.

Similar Messages

  • Consume web service I get an unable to cast array error?????

    Hi All,
    I do not know what I have done but I am getting the following error?
    Error(24,30): cannot cast array webserviceproj2.proxy.Employee[] to interface java.util.List&lt;webserviceproj2.proxy.Employee&gt;
    Here is my Scenario
    Project 1
    I have a Project which contains One class that was generated by Toplink "Employees" I have a Map with a few queries
    I Create a Java Service Facade to test and everything works fine...
    I create a session bean with a Remote, Local and Web service endpoint which generates the deploy file for me.
    I Deploy to Oracle AS 10.1.3 and test the web service. Again all is working so far.
    Project 2
    I Create an empty project and add a web service proxy, I use the WSDL from the deployed Session Bean to generate all the files. So far I have added no code.
    I create a test class. One of the methods should get a list of Employees from the web service so I can loop through the list to prove it's working, this is where it fails. For some reason findEmployees is returning a type of Employee[] rather than a List&lt;Employee&gt; which is what should be returned?
    Can anyone please help????
    List&lt;Employee&gt; emps = (List&lt;Employee&gt;)port.findEmployeesByName("Jeremy","");
    for(Iterator i = emps.iterator(); i.hasNext();)
    Employee emp = (Employee)i.next();
    System.out.println(emp.getFirstName());

    JungleTaxi Cabbie wrote:
    Csound1: iCloud: Configuring Mail with Mac OS X v10.6 or iOS 4
    Enter your Incoming Mail Server, User Name, and Password using the following settings:
    Incoming Mail Server: mail.me.com
    User Name: Your iCloud email address (excluding @me.com)
    Password: Your password
    Last Modified: Jun 27, 2013
    Maybe you should test these things before calling people out, because these settings do function perfectly well.
    iCloud is not supported on Snow Leopard or lower, why bother to mention it?
    The OP has an iCloud account, and that can not be opened without Lion or Mountain Lion (on a Mac), IOS5 or 6 (on an iPhone/iPad)
    The document I linked to is Apples documentation for iCloud on current devices,I don't care whether you believe that you know better than they do, but it will affect the people who follow your advice as it won't work
    JungleTaxi Cabbie wrote:
    Also, if you're not running Lion or Mountain Lion, there is no "Mail, Contacts & Calendars" prefpane.
    I never said that there was, perhaps you imagined it.

  • Casting Arrays

    Is there anything particularly bad with casting Arrays? For convenience, I store some instances of a class in a LinkedList. Now, when I want to get them in a nice Array, I tried this:
    ("Creature" being a class of mine)
    Creature[] creatureArray = (Creature[]) CreatureList.toArray();That resulted in a splendid ClassCastException.
    However, this works:
    Object[] creatureArray = CreatureList.toArray();
    for (int i = 0; i < creatureArray.length; i++)
        Creature name = (Creature) creatureArray;
    So, is there generally a problem with casting Arrays or is there something else that might be the problem?
    Thank you for any suggestions!

    This may be more be more efficient:
    Creature [] array = (Creature[]) creatureList.toArray( new Creature[creatureList.size()] );

  • V-cast setup issue; turning USB storage off

    .I am trying to use V-cast. Media Manager. 
    I've installed the app on my Droid X and on my desktop. I have the USB cable connected and  I have V-Case MM open on my desktop. Everything seems to be set to "Go" until I launch V-cast on the phone.
    When I do that I get the following error: "Memory card error, card mounted or not present.  Please make sure memory card is inserted and USB storage is turned off."
    I know the card is present, and mounted because the Droid X comes with the card already installed. 
    But I went to "Settings/SD card & phone storage settings" just to be sure.  It shows "Total space 14.87GB" and "Available space 14.80GB", and an "Mount SD Card" option.  "Internal phone storage" shows 6.22GB of available space.
    Now here's the rub. 
    When I plug in the USB cable in the SD card data information changes to "unavailable" and the "Unmount..." option changes to "Mount SD card".
    I'm guessing the issue is with the last part of the error message: "USB storage is turned off" but I don't know how to turn it on.
    What is USB storage?  Is it to off site storage option Verizon offers?  Am I required to "Subscribe" in order for this app to work?

    I believe you have to be in PC Mode not Mass Storage...  Try changing that under mount options.

  • Casting arrays from double to float

    Hi, wonder if anyone can help.
    I have a method of a class that creates two double arrays (the value pointed to is a double type)
    x[][]
    y[][]
    they are essentially co-ordinates. The first dimension of the array holds the polygon number, the second the point on that polygon for the x and y respectivly.
    This method is called from (and therefore the arrays returned to) a class in an applet i am designing.
    I now have to get these co-ords into a general path for display. A general path only takes float values. I have tried all the normal casting tricks to try to convert these doubles into floats and nothing is working. Do you have to do anything special because they are in arrays.
    Any help would be appriciated.

    There is nothing special about array except that you cannot cast them.
    Instead you need to create a new set of arrays and copy/cast each value individually.

  • Type casting arrays

    i m reading an array of int from ObjectOutPutStream. can any body tell how do we type cast an object to array ??

    karansha:
    I'm sure you mean you're trying to read in an int[] from an ObjectInputStream that was written to an ObjectOutputStream since you can't read from an OutputStream. Use something like this:
    ObjectInputStream in = <whatever>;
    int[] intArray = (int[])in.readObject();adramolek:
    Why should you use an Integer[] instead of an int[] for serialization? All arrays of primitives -- boolean[], byte[], double[], float[], int[], long[], short[] -- are serializable as is; there is no need to convert them to arrays of their wrapper types simply to serialize them.
    In fact, the output from the following piece of code shows exactly which interfaces are implements by an int[]:
    Class cls = int[].class;
    Class[] interfaces = cls.getInterfaces();
    for (int i = 0; i < interfaces.length; i++) {
        System.out.println(interfaces.getName());
    The output is:
    java.lang.Cloneable
    java.io.SerializableThe output is identical for each of boolean[], byte[], double[], float[], int[], long[], and short[], showing that each type is both serializable [i]and cloneable.
    Shaun                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • I want to cast Array to double[]

    I make an windowsForm class for draw graph.
    It has an input param
    public FormGraph(string title, string name1, Array data1)
    I need data of double[] type for draw graph. But I think users are want to input double[] or int[] ect...
    So I try to get data as Array type and cast it to double[].
    double[] series1 = (double[])data1;
    But it throw exception about fail to cast.
    How can I cast variable type of array to double[]?

    Another option is to combine Generics with this.
    You can use generics to allow the users to pass different types of data to a method, but type specific in a different way.
    public FormGraph<T>(string title, string name1, IEnumerable<T> data1)
    var series1 = data1.Select(x => Convert.ToDouble(x)).ToArray();
    Muthukrishnan Ramasamy
    net4.rmkrishnan.net
    Use only what you need, Reduce global warming

  • How can i cast array of string to int ?

                       while(st.hasMoreTokens()){
                                  test[count] = st.nextToken();
                                  count++;
                          }Since token deal with string, i have to pass them into String of array, but how can i convert all of them to int to perform arithmetic operation?

         public static void main (String[] args) throws IOException{
               DataInputStream dis = null;
                 String dbRecord = null;
                 int tokenCount = 0;
                 int numOfQuestion = 0;
                 int questionnAireNum = 0;
                 int postCode = 0;
                 int age = 0;
                 int gender = 0;
                 String [] response = new String[10];
                    File f = new File("polldata.txt");
                    FileInputStream fis = new FileInputStream(f); 
                    BufferedInputStream bis = new BufferedInputStream(fis); 
                    dis = new DataInputStream(bis);
                    // read the first record of the database
                    while ( (dbRecord = dis.readLine()) != null) {
                       StringTokenizer st = new StringTokenizer(dbRecord, ",");
                       tokenCount = st.countTokens();
                       numOfQuestion = tokenCount-4;
                       String rquestionNum = st.nextToken();
                       questionnAireNum = Integer.parseInt(rquestionNum);
                       String rpostCode = st.nextToken();
                       postCode = Integer.parseInt(rpostCode);
                       String rAge  = st.nextToken();
                       age = Integer.parseInt(rAge);
                       String rGender = st.nextToken();
                       gender = Integer.parseInt(rGender);
                       for(int i=0; i<numOfQuestion;i++){
                            response[i] = st.nextToken();
                       }hi how come when i cast the string as int it prompt me error as shown below ? I wonder what causes this because this is normally how i cast string to int, somehow it won work this way with token.
    Exception in thread "main" java.lang.NumberFormatException: For input string: " 3"
         at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
         at java.lang.Integer.parseInt(Integer.java:447)
         at java.lang.Integer.valueOf(Integer.java:553)
         at test.main(test.java:43)

  • Learning java programing - Array issues.

    Hi Everyone,
    I just started in java programming and into Arrays multidimensional. I started a simple 2 dimensional array with 5 names with genders. I 'm having issues because it does not want to print out the names with correct genders Male/ Female. The simple program should print out the 5 names with gender type.
    example:
    Jack - Male
    Sally - Female
    Dave - Male
    Sue - Female
    Brian - Male
    Here is what I came up with so far:
    public class Multiname
         public static void main(String[] args)
              //String[][] multiname;
              String [][] multiname =
                        {"Jack", "sally"},
                        {"Dave", "Brian"},
                        {"Sue"}
              /* multiname [0][0] = "Jack";
              multiname [0][1] = "Male";
              multiname [1][0] = "Sally";
              multiname [1][1] = "Female";
              multiname [2][0] = "Dave";
              multiname [2][1] = "Male";
              multiname [3][0] = "Sue";
              multiname [3][1] = "Female";
              multiname [4][0] = "Brain";
              multiname [4][1] = "Male";     
              //int rows = 2;
         //int columns = 2;
                   for(int i = 0; i < 4; i++)
                        {for(int j = 0; j < 2; j++)
                                System.out.println("multiname " + ": " + multiname [i][j]);               
    This is the result:
    multiname : Jack
    multiname : sally
    multiname : Dave
    multiname : Brian
    multiname : Sue
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
         at MultiD.main(MultiD.java:29)
    Can someone inform me what is wrong or missing, and what do I need to do to correct this. I'm new to this and I'm a visual person. Any assistance would be appreciated.
    Thanks,

    Welcome to the forum!
    When you post code use \ on the line before and on the line after the code to preserve formatting (read the FAQ). You can use the 'Preview' tab on the reply window to see what your reply will look like.
    Please edit your post and add the code tags.
    {quote}
    The simple program should print out the 5 names with gender
    {quote}
    How could it possibly do that when you commented out the lines the put the gender into the arrays?/* multiname [0][0] = "Jack";
    multiname [0][1] = "Male";
    multiname [1][0] = "Sally";
    multiname [1][1] = "Female";
    multiname [2][0] = "Dave";
    multiname [2][1] = "Male";
    multiname [3][0] = "Sue";
    multiname [3][1] = "Female";
    multiname [4][0] = "Brain";
    multiname [4][1] = "Male";
    When you are starting out don't use any more data than you need to get things working. You only need two name/gender combinations; any more just gets in the way.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Toshiba wireless portable HDD 1TB Canvio Aero Cast - warranty issue

    Hello,
    I brought toshiba wireless portable hard drive 1tb canvio aero cast from sharaf DG store in dubai on 22,feb,2015 and m from India,
    I asked the sales person that will I get warranty on the product in india and they said yes
    so i brought the canvio but when i operated the product yesterday for the first after watching the tutorial online i was shock as the led of battery is not showing when i put it on charge
    as the company recommend and i cross check the wire with other hard disk so it was confirm that the charger n cable is working but there is some issue with hard disk
    so i called customer care in India but they dont cater to any product brought from outside India.
    i dont know what to do.
    it will be respectful if toshiba company representative can solve my problem.
    looking forward for positive response

    Hi
    I think first of all you should check the information in the warranty leaflet which should fin in the HDD box.
    Why? Because as far as I know Toshiba Hard Drives are covered with a 2 year standard warranty, valid from the date of purchase
    Here you can find the details:
    http://www.toshiba.eu/Contents/Toshiba_teg/EU/Others/SW/WL_HDD.pdf
    There you will find also this info:
    This Warranty represents a Carry-In warranty service and is only applicable in the EMEA region (Europe, Middle East and Africa) where Toshiba or its Authorised Service Providers are located.
    Unfortunately, this means that this standard warranty isnt available and valid in India
    I think you should contact the dealer in Dubai because the dealer did not provide you correct information about the warranty.

  • Type cast array to cluster

    Is there any real difference between the 'array to cluster' function and simply type casting to a cluster?  The image below shows a simple example.  Aside from providing the names of each cluster element, the type cast function automatically sets the cluster size, which is a nice feature when working with a typedef.  I am really wondering whether there is any downside to type casting when the array and cluster elements are the same data type.
    Thanks in advance.
    Solved!
    Go to Solution.

    Type Cast man knows where I live, so my opinion is biased.  When I have to make such a conversion, which is practically never, but not equal to never, then I go with the Type Cast.  You hit the biggest points, meaningful labels and the ease of going from six to seven to eleven elements with the Type Def.  When I do this conversion it is typically because I need to do some property magic which arrays do not allow (all elements must share properties except value).  Creating a control from the Array to Cluster function is let's say a Clusterflop, from the Type Cast, exactly what I am looking for.  Besides, that Array to Cluster function obfuscates code, is always left at 9 elements, and otherwise needs to go away, or at least do this:
    http://forums.ni.com/t5/LabVIEW-Idea-Exchange/Remove-Default-Behavior-from-Array-To-Cluster/idi-p/17...
    First of all, ask yourself if you really should be doing this, if the answer is yes then I say Type Cast.

  • XML and Array issue

    I've created an array that loads data from an XML file. Now,
    when a button is pressed I want this array to delete all previous
    elements found in the array and add new elements coming from the
    same XML file. So I created a function called arrayUpdate, here it
    is...
    function arrayUpdate():Void{
    myArray.splice(myArray.length);
    When the button is pressed it first calls this arrayUpdate
    function and then calls the other function which loads the specific
    data from the XML file. But I can't get it to work. It just keeps
    adding new data to the old data. Did I do something wrong
    here?

    function arrayUpdate():Void {
    delete myArray;
    var myArray:Array = new Array();
    }

  • Internal mic array issue

    Hello,
    I am using HP Envy dv6-7267cl, I have recently upgraded from windows 8 to windows 8.1, then the hell broke loose on me, Internal microphone does not work, Camera does not work.. Validity finger sensor stopped working
    Some how I could get Finger sensor working back, However under device manager  
    Generic USB Hub (Validity Sensor (WBF) (PID=0018)), If I disable this only then Internal microphone responds.
    Webcam has not responded, Youcam software gives a msg to   " No webcam detected. try plugging in a webcam into your computer now. if you are using an integrated camera, make sure that it is turned on."
    What should I do with this disgusting laptop.. Please help..
    Thanks,
    Harish

    Hi Mpeacemaker, welcome to the HP Forums. I will assume the model number was a typo and reference the "13-2311ee". If I am wrong please let me know. I also will assume this came with Windows 8, as that is the default troubleshooting available on your computers support page. Here is the general troubleshooting to resolve microphone issues: Resolving Microphone and Line-in Problems (Windows 8)
    If this does not help, give me more details as to what you have tried.
    I look forward to your response.
    TwoPointOh
    I work on behalf of HP
    Please click “Accept as Solution ” if you feel my post solved your issue, it will help others find the solution.
    Click the “Kudos, Thumbs Up" on the bottom to say “Thanks” for helping!

  • CAST function issue

    Hi Experts,
    I have use CAST function for change INT to VARCHAR for Time data. When I run the query it through the below error
    *Data value out of range at OCI call OCIStmtFetch. [nQSError: 17012] Bulk fetch failed*
    Please let me know any suggestion.
    Thanks,
    Balaa...

    Hi bala,
    If you use cast function to convert it to varchar cast(column as char) would suffice.
    But the error might be due to the date format in your system....Try this way by giving cast('dd-mon-yy hh:mm:ss' as char) it might work.
    More info :- Convert string to a date
    Is it answered?
    Cheers,
    KK

  • What this problem? table(cast(array))

    exits in databse one type
    " type InNumberTab is table of number;"
    declare
    v_tbseq_trans:= InNumberTab(null);
    select count(*) into v_cont
    from dados_propriedade dp
    where dp.num_pessoa=p_num_pessoa
    group by num_nirf;
    v_tbseq_trans.EXTEND(SQL%ROWCOUNT);
    v_cont:=0;
    for v_cs in
    (select to_number(replace(dp.num_nirf,'-','')) nirf, max(dp.seq_transacao) seq_transacao
    from dados_propriedade dp
    where dp.num_pessoa=p_num_pessoa
    group by dp.num_nirf) loop
    v_tbseq_trans(v_cont):=v_cs.seq_transacao;
    v_cont:=v_cont+1;
    END LOOP;
    open p_cursor_prop for
    select
    from dados_propriedade dp
    where dp.seq_transacao in (SELECT column_value FROM TABLE(CAST(v_tbseq_trans as InNumberTab)));

    I'll try to guess what you mean.
    If you need to use object or collection type in SQL query you should declare in in SQL server not in PL/SQL code:
    SQL> declare
      2   type na is table of number;
      3   nat na := na(1,2,3);
      4  begin
      5   for x in (select column_value y from table(cast(nat as na))) loop
      6     dbms_output.put_line(x.y);
      7   end loop;
      8  end;
      9  /
    for x in (select column_value y from table(cast(nat as na))) loop
    ERROR at line 5:
    ORA-06550: line 5, column 56:
    PL/SQL: ORA-00902: invalid datatype
    ORA-06550: line 5, column 11:
    PL/SQL: SQL Statement ignored
    ORA-06550: line 6, column 25:
    PLS-00364: loop index variable 'X' use is invalid
    ORA-06550: line 6, column 4:
    PL/SQL: Statement ignored
    SQL> set serveroutput on
    SQL> create type na is table of number;
      2  /
    Type created.
    SQL> declare
      2   nat na := na(1,2,3);
      3  begin
      4   for x in (select column_value y from table(cast(nat as na))) loop
      5     dbms_output.put_line(x.y);
      6   end loop;
      7  end;
      8  /
    1
    2
    3
    PL/SQL procedure successfully completed.Is it your problem ?
    Rgds.

Maybe you are looking for