Casting Object array into String array throws ClassCastException [duplicate] - java

This question already has answers here:
Convert ArrayList<String> to String[] array [duplicate]
(6 answers)
Convert list to array in Java [duplicate]
(11 answers)
Closed 9 years ago.
List<String> list = getNames();//this returns a list of names(String).
String[] names = (String[]) list.toArray(); // throws class cast exception.
I don't understand why ? Any solution, explanation is appreciated.

This is because the parameterless toArray produces an array of Objects. You need to call the overload which takes the output array as the parameter, and pass an array of Strings, like this:
String[] names = (String[]) list.toArray(new String[list.size()]);
In Java 5 or newer you can drop the cast.
String[] names = list.toArray(new String[list.size()]);

You are attempting to cast from a class of Object[]. The class itself is an array of type Object. You would have to cast individually, one-by-one, adding the elements to a new array.
Or you could use the method already implemented for that, by doing this:
list.toArray(new String[list.size()]);

Related

Incomparable object types --> Object to string? [duplicate]

This question already has answers here:
make arrayList.toArray() return more specific types
(6 answers)
Closed 4 years ago.
The method I have is supposed to return a String [] so i used toArray method. But I get error regarding object cannot be converted to strings. I have initialized the list as String as well and am unable to figure out the error that I am getting. Everywhere I read, they say initialize as String and I have already done that. how can I fix it??
ArrayList<String> c = new ArrayList<String>(Arrays.asList(a));
.......(job done)
return c.toArray();
--The entire code:
public static String[] anagrams(String [] a) {
ArrayList<String> b = new ArrayList<String>(Arrays.asList(a));
ArrayList<String> c = new ArrayList<String>(Arrays.asList(a));
int l=a.length;
int i,j;
for (i=0;i<l;i++) {
for (j=i+1;j<l;j++) {
if (check(b.get(i),b.get(j))){
if (c.contains(b.get(j)))
c.remove(j);
}
}
}
return c.toArray();
}
Tryy this
return c.toArray(new String[c.size()]);
This basically initializes size of the array
There are two toArray methods in an ArrayList. From the docs:
Object[] toArray()
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
<T> T[] toArray(T[] a)
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
Right now you are using the first version, which returns an Object array. Since you want a String array, not an Object array, you must use the second version:
return c.toArray(new String[0]);
The array parameter is needed so ArrayList knows which type to return. If you provide an empty array, ArrayList will allocate a new array for the desired type. However you can also provide an array that is big enough for all elements of the list, then ArrayList will use that array instead of initializing a new one:
return c.toArray(new String[c.size()]);

Java Array Element Type [duplicate]

This question already has answers here:
How to create a generic array in Java?
(32 answers)
Closed 5 years ago.
I want to know what kinds of reference can be array elements.
I know that there're primitive types like:
String[] strs = new String[5];
But there is no
List<String>[] stringList;
However, when I new a class, there is
Class Student{
String name;
List<String> courses;
}
Student[] students = new Student[5];
It says "The element type of an array may be any type, whether primitive or reference."
I think Student is reference and List<> is also reference. What's the difference between them?
Thanks.
Anything can go in an array. Primitives, other arrays, or lists.
Any of the following are legitimate declarations:
int[] intArray;
int[][] arrayOfIntArrays;
List <String> stringList;
List <String[]> stringArrayList;
List <List<String[]>> badIdea; //list of a list of string arrays
List<String>[] array of a list of strings
etc.
An array is a subclass of Object. There is nothing special about it except that java gave it some unique syntax. Otherwise, it's just like anything else you run into in java.

Generic array creation error on ArrayList [duplicate]

This question already has answers here:
Generic array creation error
(5 answers)
How to create a generic array in Java?
(32 answers)
Closed 7 years ago.
I get the following error in my IDE "generic array creation"
I googled it but found very long explanations and didn't quite understand what the best solution is to this problem.
If anyone could suggest the best solution to this to get my code to compile...
public ArrayList<String>[] getClosedTicketIDs(Account account) {
ArrayList<String> closedSourceTickets = new ArrayList<>();
ArrayList<String> closedAccountTickets = new ArrayList<>();
// ...some unimportant to this example code...
// return
ArrayList<String>[] a = new ArrayList<String>[2]; // <-- generic array creation error
a[0] = closedSourceTickets;
a[1] = closedAccountTickets;
return a;
}
My objective is to return an array consisting of 2 ArrayList<String> (no more, no less).
You can only create raw array types. You need to do this: a = new ArrayList[2];
You cant do that but you can do
List<List<String>> a=new ArrayList<ArrayList<String>>();
but the better would be
ArrayList[] a=new ArrayList[n];
as you can fix the size in this.

Why I convert ArrayList to Interger[] is wrong? [duplicate]

This question already has answers here:
Convert ArrayList<String> to String[] array [duplicate]
(6 answers)
Closed 7 years ago.
private ArrayList<Integer> list;
...
...
...
for (int i=0; i < list.size(); i++) {
Log.e("downloadTask","resource ID is " + list.get(i));
}
Integer[] resourceId = resourceId= (Integer[])list.toArray();
before for() statement, list had already been initialized. It has three elements;
The Log message is right, but when run
Integer[] resourceId = (Integer[]) list.toArray();
it will throw Exceptions. I don't know how to solve this problem.
list.toArray() returns an array of objects (Object[]), which can not be cast to an integer array (because Object[] can contain anything, like String, Boolean, SpiderMan, not only Integer).
Try:
list.toArray(new Integer[list.size()]); //will fill and return passed array
//with all elements from list
In the future, please provide the exact exceptions being thrown (and include the stack trace) so it's easier for people to spot the problem.

Convert contents of an array list to an array [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Convert a generic list to an array
So I am trying to convert the contents of my arraylist into an array. However I keep getting the error
Type mismatch: cannot convert from Object[] to String
or the error
Type mismatch: cannot convert from String[] to String
any ideas how to solve this, I'm drawing up blanks. Thanks
Here is one way:
String[] listArr= new String[yourList.size()];
Iterator<String> listIter = yourList.iterator();
while (listIter .hasNext()) {
listArr[count] = listIter .next();
}
Note: There may be syntax errors, I just typed code here.
Try this:
String[] array = arrayList.toArray(new String[0]);
That is, assuming that the ArrayList was declared with type ArrayList<String>. Replace with the appropriate types if necessary.
Another way:
String[] result = new String[arrayList.size()];
arrayList.ToArray( result );

Categories

Resources