views:

89

answers:

4

I want to ask a Java String[] question. In the java, if a variable convents to another, it can add the (String), (int), (double),... before the variable in the left hand side. However, is there something like (String[]) in Java as I want to convent the variable into (String[]).

+2  A: 

Yes, there is (String[]) which will cast into an array of String.

But to be able to cast into a String array, you must have an array of a super type of String or a super type of array (only Object, Serializable and Cloneable).

So only these casts will work :

String[] sArray = null;
Object[] oArray = null;
Serializable[] serArray = null;
Comparable[] compArray = null;
CharSequence[] charSeqArray = null;
Object object = null;
Serializable serializable = null;
Cloneable cloneable = null;

sArray = (String[]) oArray;
sArray = (String[]) serArray;
sArray = (String[]) compArray;
sArray = (String[]) charSeqArray;
sArray = (String[]) object;
sArray = (String[]) serializable;
sArray = (String[]) cloneable;
Colin Hebert
or you must have a super class of the the array: `Object` in that case...
Carlos Heuberger
@Carlos Heuberger, I knew I forgot something, I'll edit the answer ;)
Colin Hebert
+2  A: 
  1. What you call 'convert' is actually called 'cast'.
  2. Casting variable has no effect on object itself. In other words, (String) x is not equivalent of x.toString()
  3. String[] is a perfectly normal Java class, just like any other. Try this, for example:

    System.out.println(String[].class.getName());

You can also check 'Casting Objects' section in Java tutorial:
http://download.oracle.com/javase/tutorial/java/IandI/subclasses.html

Nikita Rybak
A: 

Yes, ofcourse.

Example:

String s1 = "test1";
String s2 = "test2";
Object obj [] = new Object[]{s1,s2};
String s[] = (String[]) obj;
System.out.println(s1);
System.out.println(s2);
Nikola
`String s = (String[]) obj;` will crash, you cannot convert `String[]` to `String`...and why are you printing s1 and s2?
The Elite Gentleman
ooo, my mistake in typing
Nikola
A: 

What you want is probably not casting to String[], because your object is not a String[] but something else. What I think you are looking for would be something like this:

int someInt = 1;
long someLong = 2;
String[] strings = new String[] {
    Integer.toString(someInt), 
    Long.toString(someLong)};
Gerco Dries