954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

unable to change from arraylist to array

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)

daneuchar
Light Poster
30 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

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

JamesCherrill
Posting Genius
Moderator
6,371 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

oops thankyou you fixed it :)

daneuchar
Light Poster
30 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You