0

Need help with this..i was trying to convert Object type array to String type array by the below code:

Object matNodes[] = null;
Iterable<Vertex> vertex = tb.printNodes();
Iterator itr = vertex.iterator();
if(vertex.iterator().hasNext()){
    matNodes = IteratorUtils.toArray(itr);
}
String[] stringArray = Arrays.asList(matNodes).toArray(new String[matNodes.length]);

But getting below exception..

Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.Arrays$ArrayList.toArray(Unknown Source)

Anyone please guide me to resolve this.

K Erlandsson
  • 12,998
  • 6
  • 49
  • 66
sabi
  • 29
  • 1
  • 1
  • 5

3 Answers3

0

Use Arrays.copyOf:-

String[] stringArray = Arrays.copyOf(matNodes, matNodes.length, String[].class);

Sample Ex:-

Object matNodes[] = new Object[3];
    matNodes[0] = "abc";
    matNodes[2] = "fde";
    matNodes[1] = "qw";
    String[] stringArray = Arrays.copyOf(matNodes, matNodes.length, String[].class);
Arjit
  • 3,152
  • 1
  • 16
  • 18
0

From ArrayStoreException:

Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. For example, the following code generates an ArrayStoreException:

 Object x[] = new String[3];
 x[0] = new Integer(0);

See this link for more details

If your array matNode is type of object and all the object in that array are type of String then your program will work.
But if matNode array contains object other then String the your code will throw given exception.

Use loop instead if you are not sure about Type:

int toSize=matNodes.length;
String[] stringArray=new String[toSize];

for (int i = 0; i < toSize; i++) {
    stringArray[i] = matNodes[i].toString();
} 
Sumit Singh
  • 24,095
  • 8
  • 74
  • 100
0

Actually you are getting the ArrayStoreException because you are trying to convert an Iterator to an array in this line:

if(vertex.iterator().hasNext()){
    matNodes = IteratorUtils.toArray(itr); //itr here is an iterator
}

In other words you are trying to put an iterator in an array of Strings.

You should use itr.next() to get the iterated object and put it in the array, change your code like this:

if(vertex.iterator().hasNext()){
   matNodes = IteratorUtils.toArray(itr.next()); //Here you get the iterated object
}
cнŝdk
  • 30,215
  • 7
  • 54
  • 72