-2

I am writing a sample code to accept as many integer inputs as user provides and store them in vector list and then copy the items of the vector to int array but it shows syntax error in array[a]=list.elementAt(a);

   import java.util.Vector;
import java.io.*;
public class HelloWorld{

 public static void main(String []args)throws IOException{
        BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Vector list =new Vector();
while(true)
{
    String s=in.readLine();
    if(s.equals(""))
      break;
    int i=Integer.parseInt(s);
    Integer item=i;//autoboxing initialization of Integer object
    list.addElement(item); //adding to the list till user gives input
 }
 int array[]=new int[(int)list.size()];
 for(int a=0;a<array.length;a++)
   array[a]=list.elementAt(a);//Error is show here
   System.out.print(java.util.Arrays.toString(array));
    }
 }

If you have any other way to do this then please do share.

3 Answers3

1

You should either cast the elements to Integer :

array[a]=(Integer)list.elementAt(a);

or avoid using the raw Vector type, and specify the type of elements you intend to put in the Vector:

Vector<Integer> list =new Vector<>();

When you use the raw Vector list, list.elementAt(a) returns an Object. You can add any reference type to your list, so the elements can be automatically cast to Integer (or int).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thanks. It worked now. But doesn't the Integer object is converted automatically to int by unboxing – abhinavkrin May 04 '15 at 07:04
  • @coderabhi The `Integer` can be converted automatically to int, but an arbitrary Object can't be converted automatically to int. – Eran May 04 '15 at 07:07
0

You need to cast the value to integer. If you use Vector<Integer> instead of Vector you will be fine.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Veselin Davidov
  • 7,031
  • 1
  • 15
  • 23
0
   BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
             Vector list =new Vector();
             while(true)
             {
                 String s=in.readLine();
                 if(s.equals(""))
                   break;
                 int i=Integer.parseInt(s);
                 Integer item=i;//autoboxing initialization of Integer object
                 list.addElement(item); //adding to the list till user gives input
              }
              int array[]=new int[(int)list.size()];
              for(int a=0;a<array.length;a++)
                array[a]=(int) list.elementAt(a);//Error is show here
                System.out.print(java.util.Arrays.toString(array));
                 }
Ali
  • 1
  • 4