How to conver vector to Int array

Hi
I know toArray method can be used to convert vector to an array but what if I want to convert it to an int array?
Vector v = new Vector();
int r [] = new int [1];
v.add(2);
r = v.toArray()//gives errorHow can I cast it to return int Array rather than object array?

Vector v = new Vector(10);
for(int i = 0; i < 10; i++) {
    v.add(i);
int r[] = new int[v.size()];
for(int i = 0; i < r.length; i++) {
    String value = v.elementAt(i).toString();
    r[i] = Integer.valueOf( value ).intValue();
    System.out.println(r);

Similar Messages

  • How do I wrap and int array?

    Hello,
    this is my first time using the Java forum so I hope it can be helpful :)
    Im having a problem with my computer assignment at school. Here is the code im having trouble with
    private void writeObject (ObjectOutputStream out) throws IOException
         out.defaultWriteObject (); // do the default stuff
         out.writeObject (strokeColor);
         out.writeObject(xList);
         out.writeObject(yList);
         private void readObject (ObjectInputStream in) throws IOException,    ClassNotFoundException
         in.defaultReadObject (); // do the default stuff
         strokeColor = (Color) in.readObject ();
         xList = (Integer[]) in.readObject();
         yList =  (Integer[]) in.readObject();
         }In the readObject method, Im trying to restore the values of the arrays xList and yList by wrapping the data back to and integer array, but I keep getting an incompatible types error. Any suggestions?

    never mind, I just used some ArrayList objects instead and that solved the problem

  • How do you invoke a method with native int array argument?

    Hi,
    Will someone help me to show me a few codes samples on how to invoke a method which has only one argument, an int [] array.
    For exampe:
    public void Method1(int [] intArray) {...};
    Here is some simple code fragment I used:
    Class<?> aClass = Class.forName("Test2");
    Class[] argTypes = new Class[] {int[].class};
    Method method = aClass.getDeclaredMethod("Method_1", argTypes);
    int [] intArray = new int[] {111, 222, 333};
    Object [] args = new Object[1];
    args[0] = Array.newInstance(int.class, intArray);
    method.invoke(aClass, args);I can compile without any error, but when runs, it died in the "invoke" statement with:
    Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at Test1.invoke_Method_1(Test1.java:262)
         at Test1.start(Test1.java:33)
         at Test1.main(Test1.java:12)
    Any help is greatly appreciated!
    Jeff

    Sorry, my bad. I was able to invoke static methods and instance methods with all data types except native int, short, double and float, not sure the proper ways to declare them.
    After many frustrating hours, I posted the message for help, but at that time, my mind was so numb that I created a faulted example because I cut and pasted the static method invocation example to test the instance method passing int array argument.
    As your post suggested, "args[0] = intArray;", that works. Thanks!
    You know, I did tried passing the argument like that first, but because I was not declaring the type properly, I ended up messing up the actual passing as well as the instantiation step.
    I will honestly slap my hand three times.
    jml

  • How to pass int array as an IN parameter to PLSQL Procedure

    Hi,
    How to pass int array in java to a stored procedure througn jdbc
    and what type of data type I should declare to this IN parameter
    in PLSQL Procedure.
    Thanks,
    Simi

    Hi,
    The best way to do what you want depends on what you want.  Start by describing what you need to do.  It's best to post some sample data (CREATE TABLE and INSERT statments) and what results you want from that sample data.  (See the forum FAQ: https://forums.oracle.com/message/9362002)
    If you have ideas about how to do the job (e.g., populating a temporary table) it can be helpful to include those, too, but distinguish clearly between WHAT you need to do and HOW you might do it.
    As Bencol suggested, a SYS_REFCURSOR might be the best way to pass back the results.
    Since you didn't post your table, or even describe what you wanted to do with it, I'll illustrate using scott.emp, which is probably on your system.
    Say you wanted a procedure that took a DATE as an argument, and returned a some designated columns (empno, ename and hiredate in the example below) for all employees hired on or after the given DATE.  You might write a procedure like this:
    CREATE OR REPLACE PROCEDURE  hired_since
    (   start_date  IN   DATE
    ,   out_data    OUT  SYS_REFCURSOR
    AS
    BEGIN
        OPEN out_data FOR
            SELECT  empno, ename, hiredate
            FROM    scott.emp
            WHERE   hiredate  >= start_date;
    END  hired_since;
    SHOW ERRORS
    You can test it in SQL*Plus like this:
    VARIABLE   c REFCURSOR
    EXEC  hired_since (DATE '1982-01-01', :c);
    PRINT :c
    The output I got from this test was:
         EMPNO ENAME      HIREDATE
          7788 SCOTT      19-APR-87
          7876 ADAMS      23-MAY-87
          7934 MILLER     23-JAN-82

  • How to convert an int array to string array?

    Hi,
    Can anyone please help me with this question?
    int number={4,6,45,3,2,77};
    I like to convert this into a list and sort
    List mylist = Arrays.asList(number);
    Collections.sort(mylist);
    But first I need to convert the int array to String array.
    Please advise. Thanks.

    If you want to convert your int array to a String array, you have no choice but doing a conversion element by element in a for loop.
    However, if the sort method doesn't behave as desired, you can use the one with 2 parameters, the second parameter being a comparator class.
    Check the javadoc for more information : http://java.sun.com/j2se/1.3/docs/api/java/util/Collections.html
    /Stephane

  • Reading content of a file into an int array

    How do i use FileReader rd = new FileReader(filename) to read the contents into an int array?

    public static int[] parse_file(String filename)
         Vector vec = new Vector();
         int num[];
         num = new num[vec.size()];
         try {
              BufferedReader br = new BufferedReader(new FileReader(filename));
              String line;
              while((line = br.readLine()) != null) {
              vec.add(line);
              for (int i = 0; i < vec.size(); i++) {
              num[i] = (int) vec.get(i);
              System.out.println("Number=" + num);
         catch(IOException e) {
              System.out.println("error");
         return num;
    Maxsum.java:22: cannot resolve symbol
    symbol : class num
    location: class Maxsum
         num = new num[vec.size()];
    ^
    Maxsum.java:30: inconvertible types
    found : java.lang.Object
    required: int
              num[i] = (int) vec.get(i);
    How do i initialize the array?if i do not initialize it, there'll be array not initialized error also..How do i convert the String to int?

  • Returning int array from C to Java as method parameter

    Hello,
    I've been trying to accomplish this
    Java
    int[] myArray = ... (filled with some data);
    int retCode = myNativeCall(myArray);
    if(retCode == 0)
    doSomethingWith(myArray); //myArray gets overwritten with new data (with new size also) during the native call...
    C
    JNIEXPORT jint JNICALL Java_GenChav_rsaEncrypt(JNIEnv *env, jobject obj, jintArray myArray){
    jintArray outbuf;
    int[] new_array = .. // some function will fill this....
    int new_array_length = ...//some function will give me the new size, not big, 512 max...
    jint tmp[new_array_length]; //allocate..need something more ??
    memcpy(tmp, new_array, new_array_lenght);
    outbuf=(*env)->NewIntArray(env, new_array_length);
    (*env)->SetIntArrayRegion(env, outbuf, 0, new_array_length, tmp);
    myArray=outbuf;
    I tought this way I would have a updated myArray ints on the Java program...
    Any thought??

    user5945780 wrote:
    Ok, let's try to be constructive here...
    How I do implement a return type for my method like a int array ?First realized it has nothing to do with JNI. So the same question and answer applies to java only.
    >
    like:
    int[] return = myNativeCall();
    Yes.
    Then I will look for return[0], if it is == to 0, fine, it means a successful calculation by the native code. Not sure what that means. The structure of what you return it up to you.
    It can help when you are unsure of what to do in JNI....write a pseudo representation of what you want to do in a java method. Then translate that java method into JNI, everything in the pseudo method must be in the JNI code.

  • How do you check if a array is full?

    suppose you have a array of hmm numbers.
    How would you test if the array is full?

    What do you mean with "full"? It depends on your definition. There isn't such a thing as an "empty" array. It's values might be null and depending on your definition that might mean "empty", but it might as well not. Usually if you create an array that's bigger than the amount of storage you need right now (for example to avoid re-allocating it later on) you'll also keep another variable that tells you up to which position you already filled it:
    int[] myArray;
    int position;
    public addInt(int value) {
      if (position >= myArray.length) {
        throw new ArrayFullException();
      myArray[position++]=value;
    }

  • How to use Vector or other ArrayList etc to store my JTree??

    How to use Vector or other ArrayList etc to store my JTree??
    Dear friends,
    I have following I posted before, but not get satisfactory answer, so I modify and repost again here.
    I have following code can add classes and students in the JTree,
    in class Computer Science, it has student Bill Brien,
    in Math, no,
    Then I I add Student Nancy, Laura, Peter into Computer Science Class,
    add AAAA, BBB, CCC into Math class,
    I create a new class called Chemistry, then I add DDD int Chemistry;
    so this JTree is dynamically changed,
    [1]. How can I dynamically save my current JTree with all above tree structure and its nodes in a Vector or ArrayList(not sure which one is best)??
    see code below:
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    public class ModelJTreeTest extends JFrame {
      private JTree tree;
      private DefaultTreeModel model;
      private DefaultMutableTreeNode rootNode;
      public ModelJTreeTest() {
        DefaultMutableTreeNode philosophersNode = getPhilosopherTree();
        model = new DefaultTreeModel(philosophersNode);
        tree = new JTree(model);
        JButton addButton = new JButton("Add Class/Students");
        addButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            addPhilosopher();
        JButton removeButton = new JButton("Remove Selected Class/Students");
        removeButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            removeSelectedPhilosopher();
        JPanel inputPanel = new JPanel();
        inputPanel.add(addButton);
        inputPanel.add(removeButton);
        Container container = getContentPane();
        container.add(new JScrollPane(tree), BorderLayout.CENTER);
        container.add(inputPanel, BorderLayout.NORTH);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400, 300);
        setVisible(true);
      private void addPhilosopher() {
        DefaultMutableTreeNode parent = getSelectedNode();
        if (parent == null) {
          JOptionPane.showMessageDialog(ModelJTreeTest.this, "Select Class", "Error",
              JOptionPane.ERROR_MESSAGE);
          return;
        String name = JOptionPane.showInputDialog(ModelJTreeTest.this, "Add Class/Students:");
        model.insertNodeInto(new DefaultMutableTreeNode(name), parent, parent.getChildCount());
      private void removeSelectedPhilosopher() {
        DefaultMutableTreeNode selectedNode = getSelectedNode();
        if (selectedNode != null)
          model.removeNodeFromParent(selectedNode);
      private DefaultMutableTreeNode getSelectedNode() {
        return (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
      private DefaultMutableTreeNode getPhilosopherTree() {
        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Students");
        DefaultMutableTreeNode ancient = new DefaultMutableTreeNode("Computer Science");
        rootNode.add(ancient);
        ancient.add(new DefaultMutableTreeNode("Bill Brian"));
        DefaultMutableTreeNode math = new DefaultMutableTreeNode("Maths");
        rootNode.add(math);  
        DefaultMutableTreeNode physics = new DefaultMutableTreeNode("Physics");
        rootNode.add(physics);
        return rootNode;
      public static void main(String args[]) {
        new ModelJTreeTest();
    }the actual Tree dynamically created somehow looks like following:
                             |            1.Peter
                             |---CS---    2. Nancy
                             |            3. Laura
                             |            4.Brian
                             |
    Root(University): -------|---Math- 1.AAA
                             |            2.BBB
                             |            3.CCC
                             |
                             |
                             |---Chemistry- 1. DDDThanks a lot
    Good weekends

    you can't directly store a tree in a list.Ummm... Just to be contrary... Yes you CAN store a tree in a table.... In fact that's how the windows file system works.
    Having said that... you would be well advised to investigate tree data-structures before resorting to flattening a tree into a list.
    So... Do you have a specific requirement to produce a List? Your umming-and-erring about Vector vs ArrayList makes it sound like you're still at the stage of choosing a datastructure.
    Cheers. Keith.

  • Problem with reading numbers from file into double int array...

    Okay, this is a snippet of my code:
    public void readMap(String file){
            try {
                URL url = getClass().getResource(file);
                System.out.println(url.getPath());
                BufferedReader in = new BufferedReader(new FileReader(url.getPath()));
                String str;
                String[] temp;
                int j=0;
                while ((str = in.readLine()) != null) {
                    temp = str.split(",");
                    for(int i=0;i<temp.length;i++){
                        map[j] = java.lang.Integer.parseInt(temp[i]);
    j++
    in.close();
    } catch (IOException e) {
    System.out.println("Error: "+ e.toString());
    map[][] is a double int array. Now, the code is running through each line of the text file (with each line looking like this: 0,3,6,2,2,3,1,5,2,3,5,2), and I want to put the numbers into a corresponding double int array (which is where map[][] comes in). Now, this code WOULD work, except I need to set the sizes of each array before I start adding, but I don't know how to get the exact sizes.. how can I get around this issue?
    Message was edited by:
    maxfarrar

    You can do a two-dimensional ArrayList? That syntax
    you wrote didn't work.
    I tried doing:
    private ArrayList<ArrayList><Integer>> map;
    Your syntax is just wrong -- or, this forum software has bug in handling angle brackets.
    ArrayList<ArrayList<Integer>>...The closing angle bracket after the second 'ArrayList' is the one generated by the bug. Basically, it should be T<T<T2>> without spaces. Oh, for that matter:
    Arraylist<ArrayList<Integer>>

  • How can i maintain a dynamic array

    I want to maintain an dynamic array in my code . It shoud grow accroding to no of user inputs . 1 can entre 5 numbers and other 10 , then array size should grow orderly 5 and 10 like that . Array is int array.

    Read up on the Collections API. There is a tutorial on this site. At first blush, you want a List. If it will grow and you will not be removing and inserting constantly from the 'middle' of the list of items, then ArrayList is a logical choice as your List. Otherwise, use LinkedList. But definitely bone up on the tutorial. Understanding how Collections work is fundamental to any Java programming you will do.
    - Saish

  • How to call java method having array as argument from c++ ?

    Hello sir,
    how to call java method having array as arguments from c++;
    here is java code which is called from c++
    class PQR {
         public void xyz(int[] ia) {
         System.out.println("hi");
              for (int i = 0; i < ia.length; i++)
                   System.out.println(ia);
    suppose all jvm invocation is done...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    For someone well versed in java, C++ and JNI although tedious that should be obvious.
    For someone not well versed in all three it is going to be very difficult.
    Even for someone that does have knowledge in all of those areas coming up with a C++ interface that reflects that functionality in a dynamic way such that anyone is will to use it is going to be quite an adventure.
    At any rate to start building it you do exactly the same thing that you would in java.
    1. Extract everything in the jar via the zip package
    2. For each found instance extract all of the methods, return types, parameters, etc and build a description tree for each class.
    Doing all of that in C++ is going to take a LOT of code. If someone wanted an estimate from me it would take me 6 months to do it. And before I would even attempt it I would get them to explain to me in detail exactly how they thought they were going to use it when I was done because I can't see any reasonable way to do that.
    I left out the description tree itself. I suppose you could duplicate the entire reflection api in C++.
    Now perhaps if it was much, much more constrained, like to only those classes that implement a single interface then that would be more reasonable.

  • Filling an int array

    Hi would anyone know how to fill an int array of size 20 with all random number between 0-19 and have no duplicates in the finished array.

    Oh yeah i have code done but it doesnt want to work properly. ill show you.
    public int randomNum(int x, int y) {
                int a=Math.max(x, y);
                int b=Math.min(x, y);
                return (int)Math.floor(Math.random()*(a-b))+b;
          * Checks the index list to see if it contains the random number
          * @param num
          * @param arr
          * @return
         public boolean hasNum(int num, int[]arr){
              int n = num;
              for(int i=0; i<arr.length;i++){
                   if(arr[i] == n)
                        return true;
              return false;
          * Return an integer [] for use as index positions
          * @return
         public int[] indexList(){
              int[] list = new int[uArr.length];
              for(int i=0;i<list.length;i++){
              int r = randomNum(0,19);
               while(!hasNum(r,list)){
                        list[i] = r;
                        r = randomNum(0,19);
                   System.out.println(""+list);
              return list;

  • Converting a vector to an array

    hello :-)
    i am converting my vector into an array with this syntax:
    String[] lmname = (String[])name.toArray();
    and try to print my array with
    for(int i=0; i<lmname.size; i++)     
    System.out.println(lmname);
    unfortunately, i get this error:
    java.lang.ClassCastException
    what did i do wrong?

    -- you cannot do that...
    - if you still want to convert Vector into String[] then you can do this:
                 Vector v=new Vector();
               v.add("1");
               v.add("2");
               v.add("3");
               v.add("4");
               String strVector[]=new String[v.size()];
               for (int i = 0; i<v.size(); i++)
                       strVector=new String((String)v.get(i));
         for (int i = 0; i<strVector.length; i++)
         System.out.println (strVector[i]);
    ... By the way, you can use List instead of Vector,,,

  • Better way to sort multi dim int array

    I'm tracking key value pairs of ints. I know that the keys will not repeat. I've decided to do this in an int[][] array
    int[][] data = new int[2][many millions]This app crunches a lot of data so I'm shooting for the best memory handling. I push a bunch of key - value pairs into the array. I will likely populate many if not all data and not have to search until I'm done populating so I'm not sorting as I go.
    I know that I can sort the single dim array data[0] but how can I keep the values array data[1] synchronized? I've tried a few things, all have been successful but I'm wondering if there's a better method. Currently I create copy arrays for the keys and values, sort the original keys, and loop through the copy keys. For each copy key I binary search the sorted keys and drop the value in the correct spot. I don't like having to allocate 2X the amount of memory for the swap arrays. Any thoughts?
    Thanks
    ST

    Jos, thanks for the reply. I tried this method but I don't get as much
    storage since each internal array counts as an object.Yes I know; maybe I've got something for you, waidaminnit <dig-dig/>
    <shuffle-shuffle/> Ah, got it. Suppose you wrap your two dim array in
    a simple class that implements this interface:public interface Sortable {
         public int length();
         public int compare(int i, int j);
         public void swap(int i, int j);
    }I think the semantics of the methods are obvious. Given this interface
    you can sort anything you like using this thingy:public class HeapSort {
         private Sortable s;
         private void heapify(int i, int n) {
              for (int r, l= (i<<1)+1; l < n; i= l, l= (i<<1)+1) {
                   if ((r= l+1) < n && s.compare(l, r) < 0) l= r;
                   if (s.compare(i, l) < 0) s.swap(i, l);
         private void phase1() {
              for (int n= s.length(), i= n/2; i >= 0; i--)
                   heapify(i, n);
         private void phase2() {
              for (int n= s.length(); --n > 0; ) {
                   s.swap(0, n);
                   heapify(0, n);
         public HeapSort(Sortable s) { this.s= s; }
         public Sortable sort() {
              phase1();
              phase2();
              return s;
    }kind regards,
    Jos

Maybe you are looking for

  • Interruptions when I use "Write" and "Read" in the same vi.

    When I use "Port Write" and "Port Read" together in the same vi and I set the output to be high level, the signal becomes oscillatory. I have read one anterior message about similar problem (using "Write to Digital Line" and "Read from Digital Line"

  • Payment wizard-note 1385256

    Dears, by message 1385256 SAP changed functionality. When supplier has zero balance, is not possible to select BP in the payment wizard. Problem become, when supplier has zero balance and you create Down payment request. This request has no affect on

  • 148 skype accounts linked to my e-mail address

    I've recently received a "thank you for changing your Skype e-mail address" into my inbox. I never used Skype, so I didn't agree to any terms&conditions. There are no admin contact details on Skypes website, so I log into the "change password" to get

  • Going live check for SAP upgrade projects

    Hello, I am interested in "going live check" service and procedures for my upgrade projects. May I find any documentation? Do I have to pay for it?.. Thanking you in advance and a happy new years! Kind regards Nilüfer Çalışkan

  • Contribute freezing constantly on Mac, not Windows

    I have a customer trying to update her site on our server using Contribute. Not exactly sure of the version, but pretty sure it's CS5 (purchased about a year ago). When she tries to connect to the site, it will freeze at various stages requiring a Fo