I use the following code to convert an Object array to a String array :
Object Object_Array[]=new Object[100];
// ... get values in the Object_Array
String String_Array[]=new String[Object_Array.length];
for (int i=0;i<String_Array.length;i++) String_Array[i]=Object_Array[i].toString();
But I wonder if there is another way to do this, something like :
String_Array=(String[])Object_Array;
But this would cause a runtime error: Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
What's the correct way to do it ?
Another alternative to System.arraycopy:
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
In Java 8:
String[] strings = Arrays.stream(objects).toArray(String[]::new);
To convert an array of other types:
String[] strings = Arrays.stream(obj).map(Object::toString).
toArray(String[]::new);
System.arraycopy is probably the most efficient way, but for aesthetics, I'd prefer:
Arrays.asList(Object_Array).toArray(new String[Object_Array.length]);
I see that some solutions have been provided but not any causes so I will explain this in detail as I believe it is as important to know what were you doing wrong that just to get "something" that works from the given replies.
First, let's see what Oracle has to say
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must
* allocate a new array even if this list is backed by an array).
* The caller is thus free to modify the returned array.
It may not look important but as you'll see it is... So what does the following line fail? All object in the list are String but it does not convert them, why?
List<String> tList = new ArrayList<String>();
tList.add("4");
tList.add("5");
String tArray[] = (String[]) tList.toArray();
Probably, many of you would think that this code is doing the same, but it does not.
Object tSObjectArray[] = new String[2];
String tStringArray[] = (String[]) tSObjectArray;
When in reality the written code is doing something like this. The javadoc is saying it! It will instatiate a new array, what it will be of Objects!!!
Object tSObjectArray[] = new Object[2];
String tStringArray[] = (String[]) tSObjectArray;
So tList.toArray is instantiating a Objects and not Strings...
Therefore, the natural solution that has not been mentioning in this thread, but it is what Oracle recommends is the following
String tArray[] = tList.toArray(new String[0]);
Hope it is clear enough.
The google collections framework offers quote a good transform method,so you can transform your Objects into Strings. The only downside is that it has to be from Iterable to Iterable but this is the way I would do it:
Iterable<Object> objects = ....... //Your chosen iterable here
Iterable<String> strings = com.google.common.collect.Iterables.transform(objects, new Function<Object, String>(){
String apply(Object from){
return from.toString();
}
});
This take you away from using arrays,but I think this would be my prefered way.
This one is nice, but doesn't work as mmyers noticed, because of the square brackets:
Arrays.toString(objectArray).split(",")
This one is ugly but works:
Arrays.toString(objectArray).replaceFirst("^\\[", "").replaceFirst("\\]$", "").split(",")
If you use this code you must be sure that the strings returned by your objects' toString() don't contain commas.
If you want to get a String representation of the objects in your array, then yes, there is no other way to do it.
If you know your Object array contains Strings only, you may also do (instread of calling toString()):
for (int i=0;i<String_Array.length;i++) String_Array[i]= (String) Object_Array[i];
The only case when you could use the cast to String[] of the Object_Array would be if the array it references would actually be defined as String[] , e.g. this would work:
Object[] o = new String[10];
String[] s = (String[]) o;
You can use type-converter.
To convert an array of any types to array of strings you can register your own converter:
TypeConverter.registerConverter(Object[].class, String[].class, new Converter<Object[], String[]>() {
#Override
public String[] convert(Object[] source) {
String[] strings = new String[source.length];
for(int i = 0; i < source.length ; i++) {
strings[i] = source[i].toString();
}
return strings;
}
});
and use it
Object[] objects = new Object[] {1, 23.43, true, "text", 'c'};
String[] strings = TypeConverter.convert(objects, String[].class);
For your idea, actually you are approaching the success, but if you do like this should be fine:
for (int i=0;i<String_Array.length;i++) String_Array[i]=(String)Object_Array[i];
BTW, using the Arrays utility method is quite good and make the code elegant.
Object arr3[]=list1.toArray();
String common[]=new String[arr3.length];
for (int i=0;i<arr3.length;i++)
{
common[i]=(String)arr3[i];
}
Easily change without any headche
Convert any object array to string array
Object drivex[] = {1,2};
for(int i=0; i<drive.length ; i++)
{
Str[i]= drivex[i].toString();
System.out.println(Str[i]);
}
Related
The following code (run in android) always gives me a ClassCastException in the 3rd line:
final String[] v1 = i18nCategory.translation.get(id);
final ArrayList<String> v2 = new ArrayList<String>(Arrays.asList(v1));
String[] v3 = (String[])v2.toArray();
It happens also when v2 is Object[0] and also when there are Strings in it.
Any Idea why?
This is because when you use
toArray()
it returns an Object[], which can't be cast to a String[] (even tho the contents are Strings) This is because the toArray method only gets a
List
and not
List<String>
as generics are a source code only thing, and not available at runtime and so it can't determine what type of array to create.
use
toArray(new String[v2.size()]);
which allocates the right kind of array (String[] and of the right size)
You are using the wrong toArray()
Remember that Java's generics are mostly syntactic sugar. An ArrayList doesn't actually know that all its elements are Strings.
To fix your problem, call toArray(T[]). In your case,
String[] v3 = v2.toArray(new String[v2.size()]);
Note that the genericized form toArray(T[]) returns T[], so the result does not need to be explicitly cast.
String[] v3 = v2.toArray(new String[0]);
also does the trick,
note that you don't even need to cast anymore once the right ArrayType is given to the method.
Using toArray from the JDK 11 Stream API, you can solve the more general problem this way:
Object[] v1 = new String[] {"a", "b", "c"}; // or array of another type
String[] v2 = Arrays.stream(v1)
.<String>map((Object v) -> v.toString()).toArray(String[]::new);
String[] str = new String[list.size()];
str = (String[]) list.toArray(str);
Use like this.
I want to know if it is safe/advisable to convert from ArrayList to Array?
I have a text file with each line a string:
1236
1233
4566
4568
....
I want to read them into array list and then i convert it to Array. Is it advisable/legal to do that?
thanks
Yes it is safe to convert an ArrayList to an Array. Whether it is a good idea depends on your intended use. Do you need the operations that ArrayList provides? If so, keep it an ArrayList. Else convert away!
ArrayList<Integer> foo = new ArrayList<Integer>();
foo.add(1);
foo.add(1);
foo.add(2);
foo.add(3);
foo.add(5);
Integer[] bar = foo.toArray(new Integer[foo.size()]);
System.out.println("bar.length = " + bar.length);
outputs
bar.length = 5
This is the best way (IMHO).
List<String> myArrayList = new ArrayList<String>();
//.....
String[] myArray = myArrayList.toArray(new String[myArrayList.size()]);
This code works also:
String[] myArray = myArrayList.toArray(new String[0]);
But it less effective: the string array is created twice: first time zero-length array is created, then the real-size array is created, filled and returned. So, if since you know the needed size (from list.size()) you should create array that is big enough to put all elements. In this case it is not re-allocated.
ArrayList<String> myArrayList = new ArrayList<String>();
...
String[] myArray = myArrayList.toArray(new String[0]);
Whether it's a "good idea" would really be dependent on your use case.
assuming v is a ArrayList:
String[] x = (String[]) v.toArray(new String[0]);
There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0])).
In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.
You can follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).
This is the recommended usage for newer Java ( >Java 6)
String[] myArray = myArrayList.toArray(new String[0]);
In older Java versions using pre-sized array was recommended, as the
reflection call which is necessary to create an array of proper size
was quite slow. However since late updates of OpenJDK 6 this call was
intrinsified, making the performance of the empty array version the
same and sometimes even better, compared to the pre-sized version.
Also passing pre-sized array is dangerous for a concurrent or
synchronized collection as a data race is possible between the size
and toArray call which may result in extra nulls at the end of the
array, if the collection was concurrently shrunk during the operation.
This inspection allows to follow the uniform style: either using an
empty array (which is recommended in modern Java) or using a pre-sized
array (which might be faster in older Java versions or non-HotSpot
based JVMs).
Most answers work as accepted. But since Java 11, there's another way to use toArray() method using method reference operator or double colon operation (::).
Here's an example:
ArrayList<String> list = new ArrayList<>();
// ... add strings to list
// Since java 11
String[] strArray = list.toArray(String[]::new);
// before java 11, as specified in the official documentation.
strArray = list.toArray(new String[0]);
The Collection interface includes the toArray() method to convert a new collection into an array. There are two forms of this method. The no argument version will return the elements of the collection in an Object array: public Object[ ] toArray(). The returned array cannot cast to any other data type. This is the simplest version. The second version requires you to pass in the data type of the array you’d like to return: public Object [ ] toArray(Object type[ ]).
public static void main(String[] args) {
List<String> l=new ArrayList<String>();
l.add("A");
l.add("B");
l.add("C");
Object arr[]=l.toArray();
for(Object a:arr)
{
String str=(String)a;
System.out.println(str);
}
}
for reference, refer this link http://techno-terminal.blogspot.in/2015/11/how-to-obtain-array-from-arraylist.html
One approach would be to add the Second for Loop where the printing is being done inside the first for loop. Like this:
static String[] SENTENCE;
public static void main(String []args) throws Exception{
Scanner sentence = new Scanner(new File("assets/blah.txt"));
ArrayList<String> sentenceList = new ArrayList<String>();
while (sentence.hasNextLine())
{
sentenceList.add(sentence.nextLine());
}
sentence.close();
String[] sentenceArray = sentenceList.toArray(new String[sentenceList.size()]);
// System.out.println(sentenceArray.length);
for (int r=0;r<sentenceArray.length;r++)
{
SENTENCE = sentenceArray[r].split("(?<=[.!?])\\s*"); //split sentences and store in array
for (int i=0;i<SENTENCE.length;i++)
{
System.out.println("Sentence " + (i+1) + ": " + SENTENCE[i]);
}
}
}
ArrayList<String> a = new ArrayList<String>();
a.add( "test" );
#SuppressWarnings( "unused")
Object[] array = a.toArray();
It depends on what you want to achieve if you need to manipulate the array later it would cost more effort than keeping the string in the ArrayList. You have also random access with an ArrayList by list.get( index );
I usually use this method.
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
int[] arr = list.stream().mapToInt(i -> i).toArray();
System.out.println(Arrays.toString(arr)); // [1, 2, 3]
}
I am getting the checked items ids in ListView from List.getCheckedItemIds which returns long array, now how to convert this array to String array ?
long [] long_list = ProcessList.getCheckedItemIds();
String[] string_list = new String[long_list.length];
for(int i = 0; i < long_list.length; i++){
string_list[i] = String.valueOf(long_list[i]);
}
The question may be considered unwarranted a few years ago, but it's worth a new look now considering the recent progress in Java land with regards to the emerging Stream API.
Instead of relying on any third-party API, you can use the built-in Stream API for array operations in Java 1.8 and above.
You can now easily use
String[] yourStringArray = Arrays.stream(yourLongArray).mapToObj(String::valueOf).toArray();
And if your intention is to print yourStringArray, you can then convert it into a string using
String str = Arrays.toString(yourStringArray);
****
Lucky for us, Arrays.toString() operates on all types of arrays, so the whole thing can be simplified to just
String str = Arrays.toString(yourLongArray);
Isn't this cleaner?
You can use org.apache.commons.lang.StringUtils like this:
String[] string_list = StringUtils.join(long_list, ",").split(",");
You can leverage apache's BeanUtils to do Array conversion without doing iteration by yourself like below.
Long[] longArrays= (Long[]) ConvertUtils.convert(stringArrays, Long[].class);
Or with Java 8+,
Object[] array = ...; // or i.e. Long[] array
String[] s = Arrays.stream(array).map(String::valueOf).toArray(String[]::new);
You can make a new String array and pass the values of long array to the string array one by one:
String[] s=new String[long_list.length];
for(int i=0;i<long_list.length;i++)
{
s[i]=String.valueOF(long_list[i]);
}
Sorry for the mistakes. I've updated the code.
I am trying to write a method that takes in an Object[] that is populated with tokens and converts it to an array of integers.
I started out with an ArrayList:
ArrayList<String> colArr = new ArrayList<String>();
then populated it with tokens from a .txt file:
while(st.hasMoreTokens()){
colArr.add(st.nextToken());
}
then converted it to an Object[]:
Object[] newColArr = colArr.toArray();
I now need to write a method that converts this Object[] to an Integer so that I can add certain elements together. This is what I tried:
public static Integer[] convert(Object[] objectArray){
Integer[] intArray = new Integer[objectArray.length];
for(int i=0; i<objectArray.length; i++){
intArray[i] = (Integer) objectArray[i];
}
return intArray;
}
but got "Error: java.lang.String cannot be cast to java.lang.Integer".
use Integer.valueOf(objectArray[i]) instead of casting like (Integer)objectArray[i]
EDIT:
To clarify, remember that Integer.valueOf() is simply a boxed object around Integer.parseInt().. so you have to handle NumberFormatException.
If you are quite sure that your text file will only contain integers, you could simply have an arraylist of integers and do the Integer.valueOf(tokenizer.nextToken())
Integer.parseInt( string ); works for getting an Integer from String
loop through your array of strings and use Integer.parseInt();
You can't typecast directly from a java.lang.String to a java.lang.Integer, they are two totally different objects. Instead try doing:
Integer.parseInt(objectArray[i])
Don't forget to handle java.lang.NumberFormatException. And one more thing, you don't need to do the intermediary conversion to Object array. Unless of course your using that for something else you didn't mention. Cheers.
if you know, that the object array contains strings, you can use Integer.parseInt() to convert the String to a Integer
You can also use guava's Lists.transform.
List<String> numberList=Lists.newArrayList("1","2","3");
List<Integer> trnsList = Lists.transform(numberList,new Function<String,Integer>() {
#Override
public Integer apply(String arg0) {
return Integer.valueOf(arg0);
}
});
Integer[] intArr=trnsList.toArray(new Integer[trnsList.size()]);
I need to get a String[] out of a Set<String>, but I don't know how to do it. The following fails:
Map<String, ?> myMap = gpxlist.getAll();
Set<String> myset = myMap.keySet();
String[] GPXFILES1 = (String[]) myset.toArray(); // Here it fails.
How can I fix it so that it works?
Use the Set#toArray(IntFunction<T[]>) method taking an IntFunction as generator.
String[] GPXFILES1 = myset.toArray(String[]::new);
If you're not on Java 11 yet, then use the Set#toArray(T[]) method taking a typed array argument of the same size.
String[] GPXFILES1 = myset.toArray(new String[myset.size()]);
While still not on Java 11, and you can't guarantee that myset is unmodifiable at the moment of conversion to array, then better specify an empty typed array.
String[] GPXFILES1 = myset.toArray(new String[0]);
Java 11
The new default toArray method in Collection interface allows the elements of the collection to be transferred to a newly created array of the desired runtime type. It takes IntFunction<T[]> generator as argument and can be used as:
String[] array = set.toArray(String[]::new);
There is already a similar method Collection.toArray(T[]) and this addition means we no longer be able to pass null as argument because in that case reference to the method would be ambiguous. But it is still okay since both methods throw a NPE anyways.
Java 8
In Java 8 we can use streams API:
String[] array = set.stream().toArray(String[]::new);
We can also make use of the overloaded version of toArray() which takes IntFunction<A[]> generator as:
String[] array = set.stream().toArray(n -> new String[n]);
The purpose of the generator function here is to take an integer (size of desired array) and produce an array of desired size. I personally prefer the former approach using method reference than the later one using lambda expression.
Use toArray(T[] a) method:
String[] array = set.toArray(new String[0]);
Guava style:
Set<String> myset = myMap.keySet();
FluentIterable.from(mySet).toArray(String.class);
more info: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/FluentIterable.html
In Java 11 we can use Collection.toArray(generator) method. The following code will create a new array of String:
Set<String> set = Set.of("one", "two", "three");
String[] array = set.toArray(String[]::new)
See: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html#toArray(java.util.function.IntFunction)
Set<String> stringSet= new HashSet<>();
String[] s = (String[])stringSet.toArray();
I was facing the same situation.
I begin by declaring the structures I need:
Set<String> myKeysInSet = null;
String[] myArrayOfString = null;
In my case, I have a JSON object and I need all the keys in this JSON to be stored in an array of strings. Using the GSON library, I use JSON.keySet() to get the keys and move to my Set :
myKeysInSet = json_any.keySet();
With this, I have a Set structure with all the keys, as I needed it. So I just need to the values to my Array of Strings. See the code below:
myArrayOfString = myKeysInSet.toArray(new String[myKeysInSet.size()]);
This was my first answer in StackOverflow.
Sorry for any error :D