haltman
haltman

Reputation: 551

java change element type in array

I have a code like this:

public class Main{
    public static void main(String args[]) {
    String s="null, arco, baleno";
     Object[] arr=s.split("\\,");
     for (int i=0; i<arr.length; i++)
     {
         System.out.println(arr[i]);
     }
    }
}

I need a possibility to change type of arr[0] or other elements from String to int or other types. How can I do that?

Upvotes: 2

Views: 7251

Answers (3)

Lion
Lion

Reputation: 19047

You can change from string to int in different ways as follows.

Integer.parseInt(arr[i].toString());
Integer.valueOf(arr[i].toString()).intValue();
Integer temp=new Integer(arr[i].toString());

You can parse the elements of arr[] to int and store into another array as follows.

public class Main
{
    public static void main(String args[])
    {
        String s="1,2,3";
        Object[] arr=s.split("\\,");
        int temp[]=new int[arr.length];

        for(int i=0; i<arr.length; i++)
        {
            temp[i]=Integer.parseInt(arr[i].toString());
            System.out.println(temp[i]);
        }
    }
}

You can convert a data type to another data type as follows (using auto-boxing and unboxing techniques).

    Float f=new Float(arr[0].toString());
    f=Float.parseFloat(arr[0].toString());
    f=Float.valueOf(arr[0].toString()).floatValue();

    Double d=new Double(arr[0].toString());
    d=Double.parseDouble(arr[0].toString());
    d=Double.valueOf(arr[0].toString()).doubleValue();

    Long l=new Long(arr[0].toString());
    l=Long.parseLong(arr[0].toString());
    l=Long.valueOf(arr[0].toString()).longValue();

    Byte b=new Byte(arr[0].toString()).byteValue();
    b=Byte.parseByte(arr[0].toString());
    b=Byte.valueOf(arr[0].toString()).byteValue();

    Short sh=new Short(arr[0].toString());
    sh=Short.parseShort(arr[0].toString());
    sh=Short.valueOf(arr[0].toString()).shortValue();

    String str=String.valueOf(arr[0]).toString();

    Boolean bool=true;
    String boolStr=bool.toString();

    boolean boolPri=false;
    boolStr=String.valueOf(boolPri);

Upvotes: 2

soulcheck
soulcheck

Reputation: 36777

You can't. Java arrays store elements of single type.

That's unlike i.e. python lists where you can do

 l = ['a',2, 3.0]

In java you'll have to create a different array of the type you need and convert each element of your array accordingly i.e. by parsing it.

Upvotes: 2

sethupathi.t
sethupathi.t

Reputation: 502

try with this

Integer.parseInt(arr[i]);

assign it to new integer array like

newArray[i] = Integer.parseInt(arr[i]);

newArray is an integer array

Upvotes: 2

Related Questions