0
package aster;

import java.util.*;

public class master{
  public static void main(String[] args) {
  ArrayList<Object> arl=new ArrayList<Object>();
  Integer i1=new Integer(10);
  Integer i2=new Integer(20);
  Integer i3=new Integer(30);
  Integer i4=new Integer(40);
  String s1="tapan";
  System.out.println("The content of arraylist is: " + arl);
  System.out.println("The size of an arraylist is: " + arl.size());
  arl.add(i1);
  arl.add(i2);
  arl.add(s1);
  System.out.println("The content of arraylist is: " + arl);
  System.out.println("The size of an arraylist is: " + arl.size());
  arl.add(i1);
  arl.add(i2);
  arl.add(i3);
  arl.add(i4);
  Integer i5=new Integer(50);
  arl.add(i5);
  System.out.println("The content of final arraylist is: " + arl);
  System.out.println("The size of an final arraylist is: " + arl.size());
  
  Integer size = new Integer(arl.size());
  String []num = new String[size];

  //array list to array
  arl.toArray(num);
  for(int i=0;i<size;i++)
	  System.out.println("Array Value: " + num[i]);
  }
}

where am i going wrong i am getting this error

Exception in thread "main" java.lang.ArrayStoreException
	at java.lang.System.arraycopy(Native Method)
	at java.util.ArrayList.toArray(Unknown Source)
	at aster.master.main(master.java:32)
2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by daneuchar
1

You have an arraylist of Objects, that happen to be Integers, which you try to use to create an array of Strings. You can't store Integers in an array of Strings.
Here's what the API doc says:

public class ArrayStoreException
extends RuntimeException

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);

Edited by JamesCherrill: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.