Converting a Object[] array to an int [] array in java?

29,539

Solution 1

You can use Integer.valueOf.

Integer.valueOf((String) array [i])

The Integer class has a method valueOf which takes a string as the value and returns a int value, you can use this. It will throw an NumberFormatException if the string passed to it is not a valid integer value.

Also If you are using java5 or higher you can try using generics to make the code more readable.

Solution 2

You can implement the same using Generics, which would be easier.

List<Integer> numbers = new ArrayList<Integer> ();
Integer[] array = numbers.toArray (new Integer [10]);

Solution 3

have a try commons-lang

org.apache.commons.lang.ArrayUtils.toPrimitive(Integer[])

Solution 4

I know this is pretty late, but here are my 2 cents!!

int[] newArray=new int[objectArray.length];
Object[] objectArray = {1,2,3,4,5};

for(int i=0;i<objectArray.length();i++){
    b[i]=(int)objectArray[i];
}
Share:
29,539
javanoob
Author by

javanoob

Updated on July 10, 2022

Comments

  • javanoob
    javanoob almost 2 years

    It appears there is no easy way of doing this, but this is what i've done so far and if someone could correct it to make it work that would be great. At "newarray [e] = array [i].intValue ();" i get an error "No method named "intValue" was found in type "java.lang.Object"." Help!

    /*
    Description: A game that displays digits 0-9 and asks the user for a number N.
     It then reverses the first N numbers of the sequence. It continues this until
     all of the numbers are in order.
     numbers
    
    */
    
    import hsa.Console;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import java.util.Arrays;
    
    
    public class ReversalGame3test
    
    {
        static Console c;
    
        public static void main (String[] args)
    {
        c = new Console ();
    
        c.println ("3. REVERSAL GAME");
        c.println ("");
        c.println ("Displayed below are the digits 0-9 in random order. You must then enter a");
        c.println ("number N after which the computer will reverse the first N numbers in the");
        c.println ("sequence. The goal of this game is to sort all of the numbers in the fewest");
        c.println ("number of reversals.");
        c.println (""); //introduction
    
        List numbers = new ArrayList ();
        numbers.add ("0");
        numbers.add ("1");
        numbers.add ("2");
        numbers.add ("3");
        numbers.add ("4");
        numbers.add ("5");
        numbers.add ("6");
        numbers.add ("7");
        numbers.add ("8");
        numbers.add ("9");
        Collections.shuffle (numbers);
        Object[] array = numbers.toArray (new String [10]); // declares + shuffles numbers and converts them to array
    
        c.print ("Random Order: ");
        for (int i = 0 ; i < 10 ; i++)
        {
            c.print ((array [i]) + " ");
        }
        c.println ("");
    
        boolean check = false;
        boolean check2 = false;
        String NS;
        int N = 0;
        int count = 0;
        int e = -1;
        int[] newarray = new int [10];
    
        //INPUT
        do
        {
            c.print ("Enter a number: ");
            NS = c.readString ();
            count += 1;
    
            check = isInteger (NS);
            if (check == true)
            {
                N = Integer.parseInt (NS);
                if (N < 1 || N > 10)
                {
                    check = false;
                    c.println ("ERROR - INPUT NOT VALID");
                    c.println ("");
                }
                else
                {
                    c.print ("Next Order: ");
                    for (int i = N - 1 ; i > -1 ; i--)
                    {
                        e += 1;
                        newarray [e] = array [i].intValue ();
                        c.print ((newarray [e]) + " ");
                    }
                    for (int i = N ; i < 10 ; i++)
                    {
                        e += 1;
                        newarray [e] = array [i].intValue ();
                        c.print ((newarray [e]) + " ");
                    }
                    check2 = sorted (newarray);
                } // rearranges numbers if valid
            } // checks if N is valid number
        }
        while (check == false);
    } // main method
    
    
    public static boolean isInteger (String input)
    {
        try
        {
            Integer.parseInt (input);
            return true;
        }
        catch (NumberFormatException nfe)
        {
            return false;
        }
    } //isInteger method
    
    
    public static boolean sorted (int array[])
    {
        boolean isSorted = false;
    
        for (int i = 0 ; i < 10 ; i++)
        {
            if (array [i] < array [i + 1])
            {
                isSorted = true;
            }
            else if (array [i] > array [i + 1])
            {
                isSorted = true;
            }
            else
                isSorted = false;
    
            if (isSorted != true)
                return isSorted;
        }
        return isSorted;
    } // sorted method
    

    }

  • Admin
    Admin over 11 years
    I'm questioning the efficiency of this solution (not as if it matters significantly in this case). Is there a benefit to casting (String) then using Integer.valueOf() over (Integer) then intValue() that I'm just not seeing?
  • Arun P Johny
    Arun P Johny over 11 years
    The problem is array is not an Interger[] it is an Object[] containing String values so (Integer)array[i] should throw an class cast exception.
  • Admin
    Admin over 11 years
    Just tested that, no exception thrown here. Statement ((Integer)x[1]).intValue() returns the appropriate value where x is an array of type Object[] and x[1] is not null.
  • Arun P Johny
    Arun P Johny over 11 years
    Can you check again because it just give me java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer error on line newarray[e] = ((Integer)array[i]).intValue();. If you see the code array contains String values, java will not allow you to cast a String value to a Integer value, again it is not a compile time error it is a runtime exception, so you need to execute the code to get the exception
  • Admin
    Admin over 11 years
    Oh, that makes more sense. I was operating under the assumption that the values were stored as type int, not type String, because storing as String would be generally silly for something like this. I see the error now.
  • javanoob
    javanoob over 11 years
    All I get is an error message saying you cannot assign a java.lang.Integer expression to an int variable Can I make newarray[] type Integer and then convert it to int? If so, how?
  • javanoob
    javanoob over 11 years
    Anytime I try to use any code with "< >" I get 'invalid assignment operator'. Do you know why/how to fix?
  • javanoob
    javanoob over 11 years
    I have no idea how to go about doing whatever that means. Sorry, I have an awful comp.sci. teacher.
  • Jayamohan
    Jayamohan over 11 years
    Are you using java5 or higher version... Generics is supported only from java5...
  • javanoob
    javanoob over 11 years
    I suppose not then, I'm using something called "Ready to Program" for java
  • Vinay Yadav
    Vinay Yadav over 3 years
    Thanks, I was also about to give the same answer.