Vector or array

Hi,
I have a set of numbers say 1 to 1000 (Set A)
I want to process them one at a time and as I process them, they will create another number which will also exist in the original set A.
These numbers that exist in the set A, I want to remove and then continue to process the next number.
I have at present been working around the problem by just using a simple for loop for the 1 to 1000 and storing the numbers that need to be removed in an array.
Each step then requires me to check if the current no. in the for loop isnt in the array before processing.
This seems very wasteful and not very fast. I was wondering what woud be the best approach.
Robin

A HashMap should be pretty good for answering the question "is a given number in this set".
But before optimizing ask yourself: do you really need to? How long does the current program run? If the program is run a thousand times a day and the savings are significant then it may be worth it. If you are spending hours to save a couple of seconds from a program that gets used once a day - forget it and go spend the time at http://www.joecartoon.com/ instead.
(joecartoon not necessarily work safe - contains audio.)

Similar Messages

  • Challeging Traversal of Vector and Array

    Hi there ! I would like to render the values of this Vector and Array . How do I print it out to the browser ?
    try
    ResultSet rset = stmt.executeQuery(myQuery);
    System.out.println(" Finish Execute Query !!! ");
    /* Array Contruction */
    int numColumns = rset.getMetaData().getColumnCount();
    while (rset.next())
    aRow = new String[numColumns];
    for (int i=0; i < numColumns; i++){
    aRow[i] = rset.getString(i+1);
    allRows.addElement(aRow);
    return allRows;
    }

    Hi there !
    Thanks for your help but I managed to get it working. For references purposes, I`ll post it here.
    My problem now is this :-
    How can I issue another SQL statement and store the results in the same array?
    Pls note . One Sql per table so, that`s the issue ?
    Can someone help with a followup code ?
    try
    ResultSet rset = stmt.executeQuery(myQuery);
    System.out.println(" Finish Execute Query !!! ");
    /* Array Contruction */
    int numColumns = rset.getMetaData().getColumnCount();
    while(rset.next())
    // for every record instance aRow
    aRow = new String[numColumns];
    // store in aRow the values of the record
    for(int i=0;i<numColumns;i++)
    aRow[i] = rset.getString(i+1);
    //When aRow is full store it in the vector
    allRows.addElement(aRow);
    // when the rset finished print all the Vector
    for(int i=0;i<allRows.size();i++)
    // get returns a String[]
    String[] tmpRow = (String[])allRows.get(i);
    for(int j=0;j<tmpRow.length;j++)
    out.print(tmpRow[j]+" ");
    out.println("");
    }

  • WHY WE USE VECTOR NOT ARRAY STRING

    Hi
    I want to know why we use Vector not bufferstring.
    What is the difference Vector(1,1) and STRING[1][1]?
    Which one we will prefer?
    Why we will prefer one of them?
    Please help me to find out.

    There are huge differences between array and Vector.
    Array is a special class that allows to keep references to a number of Objects of some type. It has a maximum length set during construction, and does not offer any methods to change it's size (without defining a new array).
    Vector is a class (thread-safe unlike it's new version ArrayList) that allows to keep references to any Object (may be of different types). It doesn't have a maximum length set, and can be potentionally of any size. It allows to easily remove, add, insert new elements and keeps all the elements in the order they were added (unless some object was inserted). This is a really well written class, and I'm always using it for storing some objects.
    Hope it was helpful.

  • Vectors, lists, arrays

    Hi, I'm writing a program using a variable length sequence of boolean values. I will want to manipulate this, altering & reading etc and don't know what will be most time efficient (prog has lots of iterations and takes a while). Any ideas what'd be best for this, vectors, lists, arrays or something else?
    Cheers

    There should be no difference.
    For using List or any Collection interface, you need to use Boolean, the object though.
    You can simplify the storage by just using boolean[], the array, but with "variable length", you have to deal with growing the array. So List is simpler overall.
    --lichu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • [svn:osmf:] 11069: Minor API change: Use Vector not Array for MediaElement. get traitTypes.

    Revision: 11069
    Author:   [email protected]
    Date:     2009-10-21 16:52:10 -0700 (Wed, 21 Oct 2009)
    Log Message:
    Minor API change: Use Vector not Array for MediaElement.get traitTypes.  Approved by dev team. Should be no impact to sample apps, unit tests, or test apps.
    Modified Paths:
        osmf/trunk/framework/MediaFramework/org/osmf/media/MediaElement.as
        osmf/trunk/framework/MediaFramework/org/osmf/proxies/ProxyElement.as

    Revision: 11069
    Author:   [email protected]
    Date:     2009-10-21 16:52:10 -0700 (Wed, 21 Oct 2009)
    Log Message:
    Minor API change: Use Vector not Array for MediaElement.get traitTypes.  Approved by dev team. Should be no impact to sample apps, unit tests, or test apps.
    Modified Paths:
        osmf/trunk/framework/MediaFramework/org/osmf/media/MediaElement.as
        osmf/trunk/framework/MediaFramework/org/osmf/proxies/ProxyElement.as

  • Problem in converting vector to array of strings

    hi
    i am having a vector which in turn contains hashtable as elements
    Vector v=new Vector()
    Hashtable ht=new Hashtable();
    v.add(ht.add("key1",value1))
    v.add(ht.add("key2",value2))
    v.add(ht.add("key3",value3))
    v.add(ht.add("key4",value4))now i am trying to conver this vector in to a array of string like
    String[] str=(String[])v.toArray(new String[v.size()]);but i am getting java.lang.ArrayStoreExceptioncan anybody help me plz
    Thanks

    Hi,
    The api for public Object[] toArray(Object[] a) says
    Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array.
    ArrayStoreException will be thrown if the runtime type of a is not a supertype of the runtime type of every element in this Vector.
    The runtime type of the elements of the vector is Hashtable.
    Because String is not a supertype of Hashtable the ArrayStoreException is thrown.

  • Newbie question about using vectors and arrays

    I'm fairly new to JME development and java in general. I need some help in regards to Vectors and 1 dimensional arrays. I'm developing a blackberry midlet and am saving the queried info i pull back from my server side application with each record saved into the array and subsequently each array saved as an element in the vector, thereby creating a 2D "array".
    However I'm having a problem accessing the elements in the array. Here is a sample of what I mean and where I get stuck:
    Vector _dataTable = new Vector(1, 1);
    String[] r1 = {"a", "b", "c", "d"};
    String[] r2 = {"1", "2", "3", "4"};
    _dataTable.addElement(r1);
    _dataTable.addElement(r2);
    Object temp = _dataTable.elementAt(0); //Save the element as an new object for useNow how do I access the particular indexes of the element of the temp object? Do i need to caste it to an array? Is there another more efficient/easier way I should be storing my data? Any help would be great!
    Edited by: Sotnem2k1 on Apr 1, 2008 7:50 AM
    Edited by: Sotnem2k1 on Apr 1, 2008 7:51 AM

    Thanks for the feedback newark. I have this scenario below:
    // Class for my 1D array
    public class OneRecord {
        private String[] elementData = new String[4];
        public OneRecord() {   
            elementData[0] = null;
            elementData[1] = null;
            elementData[2] = null;
            elementData[3] = null;
        public OneRecord(String v1, String v2, String v3, String v4) {   
            elementData[0] = v1;
            elementData[1] = v2;
            elementData[2] = v3;
            elementData[3] = v4;
        public void setElement(int index, String Data) {
            elementData[index] = Data;
        public String getElement(int index) {
            return elementData[index];
    } Then in my main app I have:
    Vector _dataTable = new Vector(1, 1);
    OneRecord currRecord = new OneRecord("a", "b", "c", "d");
    _dataTable.addElement(currRecord);
    OneRecord temp = (OneRecord)_dataTable.elementAt(1);
    System.out.println(temp.getElement(0)); Are there more efficient data structures out there to save queried data from a server side app? Like I said, i'm still trying to learn the most efficient techniques of coding...esp for the Blackberry. Any suggestions would be great!

  • Copy the values of Vector to Array

    hi all,
    I have one problem that is
    I have one vector that holding objects (Ovalue)
    and Ovalue has the x,y values....
    I would like to copy the x,y values to one array
    if anyone knowd please help me
    thanks..

    Vectors have a toArray() function.

  • Converting a Vector to array

    Hi,
    How can I convert a Vector to an array of int ?
    I tried this
    //v is an object of class Vector
    int [] res=(int [])v.toArray(new int[0]);but it doesn't work so I find another way:
    //v is a Vector
    int len=v.size();      
    int[] res=new int[len];         
    for (int count=0;count<len;count++)
    res[count]=Integer.valueOf(v.elementAt(count).toString());      this works but it's inefficient , I want to do the conversion in a single line of code (if possible)
    thanks

    The code that I've posted belongs to a simple function whose aim is to fill an array with
    all the prime numbers the are less than a given value.
    The function must return an array of int (int[]).Since I don't know how many primes I will find, I need a growable array, so I decided to use Vector.If there is a better way, please tell me.
    Here is the function prototype:
    /**returns all prime numbers that are less than max_value*/
    public int[] getPrimeNumbers(int max_value){
    //function's body
    }thank you in advance

  • Vectors VS Arrays VS LinkedLists

    Hi
    I am basically looking for some info on the advantages or disadvantages of using any of the above. I would like to know how one justifies the use of one over the other.
    I would be grateful for any pointers or resources you could point me to.
    Cheers

    Use arrays if you know the size you will need, you won't be inserting or removing elements and you need highly efficient indexed access to the elements.
    Use ArrayList if you don't know how large to make the container, you need efficient indexed access to the elements, you don't need to have efficient insertion or removal of elements from the interior of the container and you don't need thread safety on the individual operations (the most common case).
    Use Vector or a synchronized ArrayList is your needs are like those for ArrayList but you need thread safety of the individual operations.
    Use LinkedList if you don't need efficient indexed access but you do need efficient insertion and removal of elements from the interior of the container and you don't need thread safety of individual operations (the usual case).
    Use the synchronized wrapper of LinkedList if your needs are like those that lead you to LinkedList but you need thread safe individual operations.
    I am sure this is documented better someplace else, but I haven't taken the time to check.
    Chuck

  • Vector with array

    If a vector contains elements which are String[2], how do i get the array element?
    Vector group=new Vector();
    String info[]=new String[2];
    here assign info some value and add to group
    // now try to print them out
    Enumeration enu=group.elements();
    while (enu.hasMoreElements() ){
    // this does not work right here. Need some refreshment.
    String result[]=(String)enu.nextElement();
    // how do i print the info[0] and info[1]
    }

    You need to cast to a String[] rather than String:
    String result[] = (String[])enu.nextElement();
    System.out.println("Result is: " + result[0] + ", " + result[1]);This is one of the reasons that many people prefer to use the following syntax to define arrays:
    String[] info = new String[2];rather than
    String info[] = new String[2];It makes it clear that info is of type String[] rather than String.
    Anyway, hope this helps.

  • Vector vs Array performance?

    Hi, I've heard some ppl says that Vector is slower than Array. Does anyone know what's the different in speed between using an array and a vector?
    Say with the same algorithm, the one uses array take 10s for 1mil iteration, how long with it take for vector?
    Thanks...

    For what it's worth adding 10K strings to various collections and accumulating 1000 results, this is what I saw:
    Vector() 0.69/0.53:
    ArrayList() 0.84/0.69:
    HashSet() 2.15/0.36:
    Vector(SZ) 0.70/0.53:
    ArrayList(SZ) 0.25/0.43:
    HashSet(SZ) 1.56/0.52:
    LinkedList() 0.86/0.60:
    A slight win to Vector unless the collections have their initial size set, in which case ArrayList comes out ahead.
    Things are a little bit different using 500K strings and doing fewer runs (in both cases I didn't time the first two runs):
    Vector() 46.20/7.77: 50 38 49 38 50 63 49 38 49 38
    ArrayList() 51.60/6.00: 50 48 51 47 51 69 52 49 51 48
    HashSet() 662.30/31.28: 648 652 652 651 652 756 652 653 652 655
    Vector(SZ) 14.90/0.30: 15 14 15 15 15 15 15 15 15 15
    ArrayList(SZ) 33.20/7.21: 26 41 26 40 26 41 26 40 26 40
    HashSet(SZ) 520.30/1.73: 523 519 520 518 519 521 519 523 522 519
    LinkedList() 345.90/31.44: 336 339 332 336 440 336 334 337 332 337
    If the initial capacity is set Vector was a clear winner for collectons of this size.
    Edited by: pbrockway2 on Jan 10, 2008 11:16 AM
    I have no fscking idea why Vector should appear to get slower when the initial size is set to 10K. But, there you are.

  • Vector  or Array List better usage

    Hi form
    For storage of large Object's Which is a better management API
    Vector OR ArrayList
    Please some one Enlightern me
    with regards
    Karthik

    Please some one Enlightern meObjects in Java are always handled using references (pointers) to the actual object values (which reside on the so called heap).
    So from the point of the size of the objects, Vector and ArrayList are equivalent. No object values are stored in them, only references to objects and references always have the same size.

  • How can we copy the elements/values of a linkedHashMap to a vector or array

    I want to copy the values in a linkedHashMap e.g. that the values are subcolumn string name and key for the linkedHashMap is the column name now, if I want to copy the vaues i.e. subcolumnName irrespective of the key(or column name) then, what can I do??
    should i use the putall() given in the api of linkedHashMap??
    any help is welcome..
    Thank you!!

    ankita.dev wrote:
    I want to copy the values in a linkedHashMap e.g. that the values are subcolumn string name and key for the linkedHashMap is the column name now, if I want to copy the vaues i.e. subcolumnName irrespective of the key(or column name) then, what can I do??
    should i use the putall() given in the api of linkedHashMap??Don't quite understand - where (what kind of collection) do you want to put them?
    I'd start out by having a look at HashMap.values().
    Winston

  • My array in the Vector is not working

    Hi all,
    I have my program sample where problem is the content of vector of (array) only produce the last items of the array, but during the for loop, my vector (m_Dist) gives the correct contents.
    my question is why is my vector produce such output?
    pls help
    tq
    import java.util.Vector;
    public class testNum{
         static double[][] dist;
         static Vector m_Dist;
         public static void main(String args[]){
              int[][] v = {{1,2,3,4,5}, {2,1,3,4,5}, {6,7,8,2,3}};
              int[][] m_Data = {{3,2,4,1,4}, {2,5,4,9,8}, {8,7,8,6,5}};
              m_Dist = new Vector<double[][]>();
              dist = new double[v.length][2];         
             for (int i=0; i<m_Data.length; i++){
                  int m_Query[] = m_Data;
              for (int j = 0; j <v.length; j++) {
              int[] example = v[j];          
                        double dis = 0.0;
              dis = EuclideanDistance(example, m_Query);
              dist[j][0] = dis;
              dist[j][1] = (double) (j + 1);
              dist = bubleSort(dist);
              m_Dist.add(dist);     
                   //test here - uncomment and will get the output it suppose to be
    //double[][] m_dist;
                   //m_dist = (double[][]) m_Dist.elementAt(i);
              //for(int j=0; j<m_dist.length; j++){
                   //System.out.println(i + " " + m_dist[j][0] + " ---> " + m_dist[j][1]);
         //System.out.println();
    //here it produce only the last items in the vector/array
              double[][] m_dist;
              for(int i=0; i<m_Dist.size(); i++){
              m_dist = (double[][]) m_Dist.elementAt(i);
              for(int j=0; j<m_dist.length; j++){
                   System.out.println(i + " " + m_dist[j][0] + " ---> " + m_dist[j][1]);
         System.out.println();
         public static double EuclideanDistance(int[] example, int[] query) {
              double dist = 0.0;
              for (int i = 0; i < example.length; i++)
              dist += (double) Math.pow(example[i] - query[i], 2.0);
              return Math.sqrt(dist);
         public static double[][] bubleSort(double[][] distances) {
              double tempDist = 0.0;
              double newOrigPos = 0.0;
              for (int i = 0; i < distances.length - 1; i++) {
              for (int j = 0; j < distances.length - 1; j++) {
                   if (distances[j][0] > distances[j + 1][0]) {
                   tempDist = distances[j][0];
                   newOrigPos = distances[j][1];
                   distances[j][0] = distances[j + 1][0];
                   distances[j][1] = distances[j + 1][1];
                   distances[j + 1][0] = tempDist;
                   distances[j + 1][1] = newOrigPos;
              return distances;

    sam.09 wrote:
    only produce the last items of the array,This makes me very suspicious. Without closely looking at your code I suspect what you are doing is simply adding the same reference to your Vector multiple times. Imagine that Fred is pointing at a piece of paper. On that piece of paper is written the word "hello". You then add Fred to your Vector. Now you change the word on the piece of paper to "dolly". Fred is still pointing to the same piece of paper although the data stored on the piece of paper has changed. You then add Fred again to the Vector. Now your Vector contains Fred twice and both of those Fred's point to the same piece of paper. You repeat this multiple times.

Maybe you are looking for

  • Itunes gives me an error message when i try to update iphone

    Im trying to update my iphone on itunes and it gives me an error message everytime, what am i doing wrong? I have the latest verison of itunes.

  • Persistent error message when trying to load a VOD show

    For the past few weeks, I keep getting an error message whenever I try to watch anything on VOD. The message says try again later but after repeated attempts it ususally doesn't work. Although, on one or two occasions I finally got the program to loa

  • Host command not working properly

    Hi, I am using oracle forms 10.1.2.0.2. In my form, I need to call a unix shell script. { Oracle forms will run on application server. Unix will run in a development server. (Both the servers are different) From forms, if I click a button, it should

  • ORB - Load Balancing ?

    Hi, All. I really need to know is it possible to use the ORB in Load Balancing mode. For example: I have a few ORB (on different machines) and when the user establish connection to the one of them, the ORB redirect the request to some other ORB in th

  • I have a black screen after boot up but the mouse is behaving normally. What's wrong?

    Hi, today I turned on my Pavilion DV9500t after shutting it down for an hour. It booted up Windows 7 64-bit normally (the welcome screen was lasting longer than usual) but instead of going to my desktop the screen went to black with the cursor behavi