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[])
.
views:
89answers:
4
+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
2010-10-07 07:20:55
or you must have a super class of the the array: `Object` in that case...
Carlos Heuberger
2010-10-07 08:35:44
@Carlos Heuberger, I knew I forgot something, I'll edit the answer ;)
Colin Hebert
2010-10-07 08:36:42
+2
A:
- What you call 'convert' is actually called 'cast'.
- Casting variable has no effect on object itself. In other words,
(String) x
is not equivalent ofx.toString()
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
2010-10-07 07:22:34
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
2010-10-07 07:22:36
`String s = (String[]) obj;` will crash, you cannot convert `String[]` to `String`...and why are you printing s1 and s2?
The Elite Gentleman
2010-10-07 08:13:35
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
2010-10-07 07:24:30