Invalid casts - Object and Integer

OK, I have got myself confused with casts. I have written this code, which I have [bold]SUBMITTED[bold] to University (so if you change it you are not helping me cheat...) . It doesn't compile and I am out of ideas why. The problem is the last method returnEvenNumbers(). Please could someone help me learn how this should be used by turning this into running code.
* Filename: RandomNumberArray.java
* Author: Steven Lane
* Email: [email protected]
* Created on 17 February 2002, 17:53
* Course: KIT eLearning, MSc in IT, University of Liverpool, UK
*         MSC-JV0020110-03
* Purpose: This class creates an uncostrained array of length L passed as int on instantiation.
*          The array is populated with (pseudo) random numbers.
*          Methods contain a filter for even numbers, which is pushed onto a stack.
* Version: 0.2
//package com.thinkcorporation.week6;
// ------------------- Import Packages -------------------
import java.util.*;
// ------------------- Class Heading -------------------
public class RandomNumberArray extends java.lang.Object {
    // ------------------- Field Defintions -------------------
   private Stack stkEvenNumbers = new Stack();
    private int [] rndNoArray;
    //private int [] evenNoArray;
    private Integer evenNoArray[];
    // ------------------- Constructors -----------------------
    public RandomNumberArray(int length) {
        rndNoArray = new int [length];
        populateRndNoArray();
    //------------------- Methods -----------------------------
    private void populateRndNoArray() {
        Random rnd = new Random();
        for(int counter = 0; counter < rndNoArray.length; counter++) {
            rndNoArray[counter] = rnd.nextInt();
    public void evenNumberFilter() {
        for(int counter = 0; counter < rndNoArray.length; counter++) {
            if (rndNoArray[counter]%2 == 0)
                stkEvenNumbers.push(new Integer(rndNoArray[counter]));
    public int [] returnEvenNumbers() {
        if (!stkEvenNumbers.empty()) {
            evenNoArray = new Integer [stkEvenNumbers.size()];
            evenNoArray = (Integer)stkEvenNumbers.toArray();
        return evenNoArray;
}You help is much appreciated.

The root of the problem is a difference between primitive types and objects. The Stack.toArray() method returns an array of Objects (Object[]), which you can cast to an array of Integer objects (Integer[]):
evenNoArray = (Integer[])stkEvenNumbers.toArray();However, your return type for that method is int[] - a primitive types, not objects. Meaning that you either have to step through the array and build an array of ints (using Integer.intValue()), or you have to change the return type of your method.

Similar Messages

  • Acrobat.exe closed by Windows & "invalid annotation object"

    While I am editing comments with Acrobat 9.3.1, I get a Windows error "acrobat.exe ..... closed by Windows"
    Then when I open the PDF document, I get "invalid annotation object" error, and the file is corrupted and not usable any more.
    Please advise me what steps I need to take to this frequent errors on my computer.  Thanks.

    I too had a Multi Page PDF that had the same "invalid annotation object".
    I was able to open & use the damaged  using Tracker Software - PDF Viewer - PDFXCview (free software - Google it)
    The file opened without error in PDFXCview and I was able to save it, but reopen in Acrobat still had the error.
    I re-opened it in PDFXCview and deleated the comments on the page that Acrobat reported the "invalid annotation object", and was able to save the file, which now opens in Acrobat without the error.

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

  • Why is the Integer wrapper class object and primitive object equal ?

    This is my code :
    package obectorientation;
    public class oo3 {
         public static void main(String[] args) {
              int x=1; float y=1.0F;
              int x1=1;
                                    Integer y1= new Integer(1);
              if(x1==y1)
                   System.out.println("Equal");
              else
                   System.out.println("NOT Equal");
    O/P : EqualMy question is why are x1 and y1 equal ? Won't y1 be a different object and x1 just a primitive variable ?
    Thanks in Advance.

    Specifically, it's because y1 gets unboxed before the comparison. What's really happening is effectively: if ( x1 == y1.intValue() )

  • Had Lion 10.7.3 and spctl enabled, after upgrading to 10.7.4 i got this error message: 'error: invalid API object reference'

    I had Lion 10.7.3 with spctl enabled, few days ago i had thru Software Updates > Upgrade to 10.7.4; i upgraded but this time when im trying to install an program i have the message that producer is not signed or software was from AppleStore so i tried to disable on Terminal, but i got this message:
    'error: invalid API object reference'
    i guess now i cant install anything because either i want to enable or disable the result is the same.

    I have this same trouble with an IMac, was also 10.7.3 with spctl enabled, and after upgraded to 10.7.4, i cant install anything.

  • Moving object and selection on integer pixel only?

    Hello,
    I am working on Flash CS5 , and I would like to "lock" any  moves or selection on the pixel grid.
    For example if I am moving with my mouse a square placed at  x:10 and y:56 I want to have someting  like x:456 and y:78 and NOT x:456,4 and y:78,8
    Same thing for the selection, it select sometimes half of a pixel or  a quarter, and it is very anoying... I am loosing a lot of time to check every element each time I placing, moving or selecting or creating to be sure it is an integer number.
    Is there a posibility to do that?
    thanks a lot.

    Ho dear...
    I tried that but it seem not working...
    in fact I just understand, if you have an element placed at x=10.47 px if you check the snapping on pixel it will keep the 0,47px shift...
    so I have to give it and integer number and then it will snap on the grid
    thanks a LOT

  • Invalid cast type error

    Hello,
    I create a new class object at runtime using:
    Class dmClass = Class.forName(dmClassName);
    I want to be able to use the Class object, dmClass, to cast new objects but I can't seem to get this to work. I've tried:
    (dmClass) .......
    (dmClass.getName()).....
    But I get an Invalid Cast type expression error.
    How can I use dmClass as the cast type in a statement?
    Thanks
    Glenn

    Ok,
    I have:
    class DataManager
    class SasDMImp which implements DataManager
    I do the following:
    String dmClassName = "SasDMImp";
    Class dmClass = Class.forName(dmClassName);
    I now want to use the SasDMImp class to cast a new object and this is the part I'm having trouble with.
    If I hard code the class name I use:
    SasDMImp dm = (SasDMImp) Naming.lookup("rmi://" host registry);
    I want to replace the hard coded SasDMImp with dmClass but I get the Invalid Cast type when I do this.
    Hope this helps.
    Glenn

  • Unable to cast object of type 'Microsoft.VisualStudio.TestTools.UITesting.UITestControl' to type 'Microsoft.VisualStudio.TestTools.UITesting.WinControls.WinComboBox'.

    Hi,
    I used to cast the UITestControl to WinComboBox in CodedUI Test and it throws the Invalid Cast Exception
    Here is my code snippet:
    in this code, CalcButtonNew() method return UITestControl object and i am trying to cast it to WinComboBox.
    Thanks in Advance,
    Selvaraj C
    Selvaraj

    Hi Selvaraj,
    According to your description, could you please tell me why you want to cast it to WinComboBox?
    Could you please tell me where you hand code for the cast it to WinComboBox, is it in the UIMap.Designer.cs file or other .cs file?
    In addition, as you said that since the CalcButtonNew() method return UITestControl object. Now, you are trying to use the CalcButtonNew() method return WinComboBox object.
    I doubt that you may be not cast UITestControl to WinComboBox successfully by handing code.
    Since when we playback the UI action by the hierarchy to search the UI Map Control object in coded UI test. If the CalcButtonNew() method reture object is UITestControl, but you want to cast the UITestControl object directly to WinComboBox object. The
    CalcButtonNew() method will not search the WinComboBox control directly by the searchproperties so that you will not cast ITestControlto WinComboBox successfully.
    If I misunderstanding your issue, please tell me more detail information about your issue.
    If possible, I suggest you can share me your sample about your issue.
    Best Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Conversion of object into integer

    hi
    How to convert Object into integer.
    I want to get value of JTable cell.So im doing
    for(int i=0;i<4i++)
    String value=(String) JTable.getValueAt(i,2);
    s.o.p("Table value :"+JTable.getValueAt(i,2));
    int changedValue=Integer.parseInt(Value);
    s.o.p("Changed value :"+value);
    }JTable.getValueAt(0,2) : 0
    JTable.getValueAt(1,2) : 0
    JTable.getValueAt(2,2) : 2
    JTable.getValueAt(3,2) : 4
    Theses are the respective values of the respective row positions
    Im able to get values of 1st row and 2nd row which are of 0 values
    But the value of third row and 4th row im gettin an exception
    java.lang.Integer cannot cast to java.lang.String
    please help anyone

    If the data in the model is of type Integer you can't cast it to String.
    You need to cast this to Integer and call intValue method to get as int.
    If you want further help post a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html] that demonstrates the problem.

  • Casting object after JSON decoding

    Hi,
    Im currently lerning about Flex and how to exchange data with PHP. I'm using JSON to send data from the server, and using corelib to decode it, then I wish to do something like this:
    user  = JSON.decode(rawData) as User;
    Because I have binds to the "user" properties and want them to be updated with the data from the decoder, but the casting fails leaving a null object, even tho Im sure the properties of both objects are the same.
    In the end I have to do something like this:
    var temp:Object = (JSON.decode(rawData));
    user.id = temp.id;
    user.name = temp.name;
    user.email = temp.email;
    //etc...
    So is there an "automatic" or better way of doing this?
    Thanks a lot.
    PD: Sorry for my bad english.

    judas1 wrote:
    I have following problem.
    Object[] myArray;
    need to delcare myArray later and so..
    if(...){myArray={3,4,5};}
    else(....){myArray={'a','b','c'};}
    of course i can create new variables and cast to them;
    Integer[] arrayInt; /// arrayInt=(Integer[])myArray;
    Character[] arrayChar; ////............
    but the problem is i wanna use one variable name in code after that. Only myArray!!!
        Object[] arr;
        if (...) {
          arr = new Integer[5];
        else {
          arr = new Character[5];
        }Of course, you'll still only be able to only operate on the individual elements as Objects, unless you cast them, so you gain nothing by using Integer[] vs. Character[].
    1. Is there a way to change the type of given variable? No, and if you think you need to, you've almost certainly got a problem in your design.
    2. Or how to find variable type and use it for dynamical declaration?
    for instance
    <type of any variable> c= new <type constructor>The type of a variable? You don't need to. You know it at compile time.
    The class of an object? You can use things like getClass, instanceof, isAssignableFrom, but if you need to do this, there's a good chance you're taking the wrong approach.
    Maybe if you step back a bit and expain what you're trying to accomplish that you think will be facilitated by changing or detecting a variable's type, someon might be able to give you a better approach.

  • T cast(Object obj)

    Hi,
    What is the actual use of this method T cast(Object obj) that "casts an object to the class or interface represented by this Class object." ?
    If we pass the class token as a parameter then we already know what type it is and this seems to be the only way to to determine the concrete type at runtime. How is this method used ?
    Thanks,
    Mohan

    Class.cast helps you avoid an "Unchecked" warning. That's about all there is to it. Example:
    import java.util.HashMap;
    import java.util.Map;
    public abstract class Factory<T> {
         public abstract T newInstance();
         public static <TT> TT createObject(Class<TT> clazz) {
              Factory<?> factory = factories.get(clazz);
              if(factory == null)
                   throw new IllegalArgumentException("invalid class "+clazz.getName());
              return (TT)factory.newInstance(); // Unchecked warning
         public static <TT> void registerFactory(Class<TT> clazz, Factory<? extends TT> factory) {
              factories.put(clazz, factory);
         private static final Map<Class<?>, Factory<?>> factories = new HashMap<Class<?>, Factory<?>>();
    }The line with the comment will trigger an "Unchecked" warning, which could be avoided by using
    return clazz.cast(factory.newInstance());

  • Problem with Retrieving objects and using info...

    Ok heres my problem.
    I have implemented a Queue using a linkedlist in java. Ok then i created a new object(in its own class - called Data) with two values, amount and price. I want the queue to store these two values in one Node. So i pass the values to it like this:
    Data A = new Data();
    A.price = Intger.parseInt(jTextField.getText());
    A.amount = Integer.ParseInt(jTextField.getText());
    Now I pass the Queue like this
    Queue B = new Queue ();
    B.enqueue(A);
    Which seems to work fine, the problem is that I need to work with the numbers in the Queue, update them, put them back and retrieve them.
    So I create a new Data object and try to dequeue like this:
    Data C = new Data();
    C = B.dequeue(); //So i can work with the two values
    but this doest work. It gives me the error that it needs an object.
    Am I doing it right?
    Anyone got any better ideas on how to do this? - Passing and retrieving two values to one Node.
    Plz help, im a newbie in Java, and cant find any tutorials on the internet.

    why don't you use vector.
    Vector queue = new Vector();
    Data a = new Data();
    a.price = Intger.parseInt(jTextField.getText());
    a.amount = Integer.ParseInt(jTextField.getText());
    queue.addElement(a);
    Data c = new Data();
    c.price = Intger.parseInt(jTextField.getText());
    c.amount = Integer.ParseInt(jTextField.getText());
    queue.addElement(c);

  • "Invalid Annotation Object" error

    I'm using Windows XP Pro (SP3) on a 2.66 GHz, 2 GB RAM computer, and while working in an Adobe Acrobat 9 document, I had just saved the file (CTRL+S) and the document froze and I got a Windows error box that asked if I wanted to send an error report, which I did. When I opened Adobe again, it asked if I wanted to open the last file which didn't save correctly, which I did.
    Then when I proceeded to work in the document and tried to highlight a sentence I was going to delete, I got an Adobe Acrobat popup box that said "Invalid Annotation Object. OK" but no matter how many times I clicked on "OK," the box kept popping up and wouldn't go away. I tried saving a copy of the document, but the same box was in it and wouldn't go away. I couldn't even work in the document to extract pages or anything else. Huge problem!
    Does anyone know what can I do to resolve this problem? (This happened on a Saturday when Adobe phone support is not accessible.)

    On 3/24/2015 same problems, after Adobe Acrobat 9 pro. crashed while I added text boxes.. When I opened Adobe again, Yes to open the last file which didn't save correctly, then "Invalid Annotation Object" errors on my .pdf file of 96 pages
    - first, I had to acknowledge/click the OK button until all " invalid annotation objects" error pop-up windows are gone
    (for my file with 96 pages, i had to hit the OK button more than hundreds times - need patience)
    - then found out (later) that what I did turn out to be the same steps as following post by davidsdomingo in adobe.forums
    davidsdomingo May 28, 2009 1:39 PM (in response to (Holger_Wulf))
    Here is a technique for identifying all the pages that have invalid annotation objects on them:
    1. Document > Extract Pages ...
    •Select the checkbox for "Extract Pages As Separate Files"
    •Set the destination to a 'dedicated' folder that won't contain any other files -- that way, you can simply delete the folder when this process is done.
    •Click OK.
    2. During the extraction, click OK in all the message boxes that appear.
    3. After the extraction, look in the destination folder to see which pages are missing. Those are the pages that have invalid annotation objects.
    From this point you can try to delete the objects, or simply delete and replace the pages, or implement a different solution. Hope this helps someone.
    - after extract the 96-pages file into individual files into a dedicated folder, only 95 got extracted and page 1 was not/can not be extracted.
    - I then combined the 95 good extracted pages into a new file name .pdf
    - then inserted a good page 1 without error (from the file that was saved previous day, prior to all the changes I made on the corrupted file), re work on page 1
    - delete the bad file.
    Hope this helps someone.

  • "Invalid annotation object" on only two of six computers.

      When searching for the resolution to this error I keep seeing that the PDF is corrupt when people get the error "Invalid annotation object".  But I have a office that has eight workstations and only two are getting the error.  To further complicate issues I downloaded Adobe Reader on one of the machines and it does not get the error either.  All of the machines on the network are using Adobe Acrobat 9.
    The steps we have taken to try to resolve the issue on one of the computers:
    Ran the repair of Adobe from the help.
    Checked for updates.  None were found, it was fully updated.
    Downloaded malware scanners - RKill, Malwarebytes and AdwCleaner.  All found nothing.
    Removed Adobe Pro and tried Adobe Standard.
    After all these steps we still get the error on the machine, but if we go to the computer in the next room it will open it fine with no errors.  We can also open the same document on that computer with Adobe Reader and get no errors.
    One way to bypass the error is to use the arrow keys to navigate the document.  The error only happens when navigating by using the mouse.
    Any and all help would be greatly appreciated.
    Thank you.

    Jenny,
    Look at where the problem computer is getting its time/date from (System Preferences>Date/Time), then compare that to one of the functional computers. It might not be syncing up with the Exchange server time-wise, which will cause problems.
    Good luck

  • Adobe "Invalid annotation object" error

    We recieve a specific error message on a few PDFs. Some from documents converted from 2007 Word and others out of Outlook 2007 through the PDF print function.  While moving the mouse over certain comments the users has placed on the document in the PDF format, Acrobat 9.9.3 throws this error. We've tried to delete the bad refs and other times have just started a new document, print to PDF while starting over.  Any ideas on why this is happining, what might be causing this and what we can do to reslove this problem.  I cannot seem to duplicate the problem a few see.  Any thoughts or solutions would be greatly appreciated. Best regards, Brian

    On 3/24/2015 same problems, after Adobe Acrobat 9 pro. crashed while I added text boxes.. When I opened Adobe again, Yes to open the last file which didn't save correctly, then "Invalid Annotation Object" errors on my .pdf file of 96 pages
    - first, I had to acknowledge/click the OK button until all " invalid annotation objects" error pop-up windows are gone
    (for my file with 96 pages, i had to hit the OK button more than hundreds times - need patience)
    - then found out (later) that what I did turn out to be the same steps as following post by davidsdomingo in adobe.forums
    davidsdomingo May 28, 2009 1:39 PM (in response to (Holger_Wulf))
    Here is a technique for identifying all the pages that have invalid annotation objects on them:
    1. Document > Extract Pages ...
    •Select the checkbox for "Extract Pages As Separate Files"
    •Set the destination to a 'dedicated' folder that won't contain any other files -- that way, you can simply delete the folder when this process is done.
    •Click OK.
    2. During the extraction, click OK in all the message boxes that appear.
    3. After the extraction, look in the destination folder to see which pages are missing. Those are the pages that have invalid annotation objects.
    From this point you can try to delete the objects, or simply delete and replace the pages, or implement a different solution. Hope this helps someone.
    - after extract the 96-pages file into individual files into a dedicated folder, only 95 got extracted and page 1 was not/can not be extracted.
    - I then combined the 95 good extracted pages into a new file name .pdf
    - then inserted a good page 1 without error (from the file that was saved previous day, prior to all the changes I made on the corrupted file), re work on page 1
    - delete the bad file.
    Hope this helps someone.

Maybe you are looking for