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
  • 13,408
  • 6
  • 51
  • 67
sabi
  • 29
  • 1
  • 1
  • 5

2 Answers2

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,290
  • 1
  • 17
  • 18
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
  • 31,391
  • 7
  • 56
  • 78