ArrayList / Vector

Hello All,
I put the result from the database as a list of transfer objects ...is it better to use ArrayList or Vector to store them and use them in my action, jsp etc......I know using vector adds the synchronization overhead but someone advised that storing data in a vector is more advantageous...
Help is greatly appreciated...
Thanks,
maithri...
Message was edited by:
Maithri

Typically, Vector is only recommended when your code needs to run in an older jvm, say version 1.2. Otherwords, array list is almost always recommended.
Even when you need synchronization, the ArrayList can become synchronized, and since you have to do that explicitly, a maintainer knows that you are doing operations that require synchronization, as opposed to using Vector, where you get synchronization whether you want it or not, so that doesn't tell the maintainer much.
- Adam

Similar Messages

  • ArrayList = Vector  | ArrayList Vector | ArrayList == Vector

    I want to know when we should use ArrayList instead of Vector, or vice-versa. I know that Vector is synchronized and ArrayList is not. But someone said that ArrayList is faster. This case also happens with Hashtable and HashMap.
    Can anybody help me?

    In new code, use ArrayList unless you are using something in Swing (or anything else) that was defined to require a Vector (done that way because Vector was the only thing around at the time, I think). If you want a synchronized List, use:
    List myList = Collections.synchronizedList(new ArrayList());Same for Hashtable/HashMap
    Map myMap = Collections.synchronizedMap(new HashMap());

  • Why Arraylist better than vector?

    Hi,
    Why Arraylist better than vector?.....i heared about it that fast then vector......how it's possible ?.....how can we find out....?

    ArrayList is faster then vector.because in vector class all the methods are synchronized.so it is obvoiusly slow.Not everything that appears obvious is actually true.
    add more object into Arraylist and vector say(1000).we have a method called currentTimeMillis() in System class .
    use that and try to iterate both (arraylist,vector) objectIf you had ever done this test (use 100000 rather than 1000 as the resolution of currentTimeMillis() is too course), then you would know that Vector is faster more often than not:new List()      new List(N)
    Add+Iterate     Add+Iterate     Add Only        Iterate Only
    ArList  Vector  ArList  Vector  ArList  Vector  ArList  Vector
    609     516     250     250     63      94      109     125
    562     516     250     266     78      94      125     109
    609     500     266     250     78      93      141     110
    532     547     250     265     62      93      110     125
    547     500     250     265     78      94      125     109
    547     500     266     265     62      94      109     109
    547     500     250     281     78      78      125     109
    ms averaged over 7 runs:
    565     511     255     263     71      91      121     114
    jdk 1.4.2_07 Windows client
    N = 1000000 The vector wins when you don't know the size it's going to end up (its capacity increases by 2 rather than 1.5 each time it grows, so there are fewer array allocations). There's no significant difference between the two on iteration. It is only when you are adding to a Vector that already has sufficient capacity that there's a measurable difference.
    Anything that requires contension on the locks will probably adversely affect the Vector's performance.
    Pete

  • How to use lists or vectors and things?

    Hello !
    I started to code with java about year ago and the first jdk that i used was 1.5.0. Since 1.5.0, generics have been supported and I think that linkedlists, arraylists and whatever have been made differently. I can't use these generics in my mobile applications so I don't how to use vectors and stacks etc, different way in my applications.
    When I used (for instance) arrayists with jdk 1.5.0 or 6, I did it like this:
    ArrayList <AL> al = new ArrayList <AL>();
    void something(){
    for(AL a : al){
    //do something
    But how do I do these with mobile things, and whats the most similar thing compared to linkedlist and arraylist, vector? I really don't know how to add and remove things with these. If someone can point a good tutorial or thread, I would really appreciate that.
    Edited by: RandomNero, for a third time in a row, on Dec 13, 2007 1:42 PM

    Hello,
    there's no typed vectors on J2ME,
    please check out this link : http://java.sun.com/javame/reference/apis/jsr118/java/util/Vector.html
    to know more about J2ME vectors.

  • I wanna sort my arraylist

    If I wanna sort my arraylist, can I make it???How?
    Thanx!

    Do you know how to use interfaces? Do you understand OOP and Java? Once nice thing about using generic types like an interface, is that you can easily switch out different algorithms. For example, if you are doing something like this:
    ArrayList myList = new ArrayList();
    and throughout your code you have methods like:
    public void doSomething(ArrayList list)
    you limit youself to using nothing but ArrayLists. What happens if your code suddenly is used by more than one concurrent person? You will no doubt run into mult-threading issues using an ArrayList. However, Vector, which is identical to an ArrayList but is thread-safe, can be swapped for an ArrayList with no changes to your code. You MUST use the methods defined in the interface however, when working on the ArrayList or Vector. As an example, there are times when you may want to "speed up" your code. When using a Vector, you lose a lot of speed because a Vector has a lot of syncronized overhead in it. This is to ensure that multiple threads do not lock or cause any problems while accessing the same Vector in memory. At times, you may find out that a certain Vector is NEVER accessed by more than one thread. Therefore, its a perfect candidate for turning into an ArrayList, as the ArrayList has no synchronized overhead and is thus much faster. But, if you are not using the List interface methods, you may find you need to change a lot more code for this to work.
    List is an interface (java.util.List) that defines methods like add, remove, get, and so on. As the other replier said, you can use the Collection framework to sort a list, and do other things with it. If you use a Vector ad usee addElement(), removeElement, etc, they wont work with ArrayList or LinkedList. The List interface is implemented by ArrayList, Vector and LinkedList. Each has their benefits. For example, if you write a program using a Vector, and it does a LOT of moving items back and forth (such as sorting), a LinkedList will be faster because the way they work, they just move a pointer to move the entire contents of the list. A Vector and ArrayList have to copy the data. However, searching is done much faster on Vectors and ArrayLists. So if you need to do a lot of searching, then one of those two would be better. If you need to do all three (or more), then you need to experiment. The nice thing is, as long as you use the List interface everywhere (except when instantiating the objects), you can simply do a find/replace in your code to replace ArrayList with Vector or LinkedList and you are all set.
    Hope that helps.

  • How to get the subclass from a super class( or interface)

    hi,
    I want to get subclass from a super class (or a interface), how to do that? the subclass of a interface means the class implementing the interface.
    for example;
    List ls;
    I want to get the subclass of ls, i.e., LinkedList, Stack, Vector......
    AbstractList al;
    the subclass of al, i.e., ArrayList, Vector.......
    thanks
    Aiwu

    List ls = new ArrayList();Since ls has been declared as a List we can only use List methods
    with it. This is a good thing because we might later want to change
    it to some other sort of List.
    I want to get subclass from a super class (or a interface), how to do
    that?The instance of the subclass declared above did not really come
    from the super class. A class "knows nothing" about its
    subclasses: many sub classes would not even exist at the time
    the class was written.

  • How to show warning message in am

    How to show warning message in am but not Stop , it still can go ahead.
    Thank you very much.

    jamras ,
    If i got you correct you wanna show user a list fo warnings after that have occured in some method in AM, and show them to user collectively, and the processing of the page should not stop in the above. What you need to do for it, is instead of throwing warning message in AM, collect all warnings in a arraylist or vector. when you navigate back to CO, iterate through this arraylist/vector and for each use pagecontext.putDialogmessage(oaexception).In this way you will be able to show all warning messages on page and your processing will not stop!
    --Mukul                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Hierarchical data with SQLAssembler: pointers vs ids

    Hi!
    Ive got parent-children nodes that I need to store and retrieve from an SQL database, using SQLAssembler. The parents and children are a recursive tree, all of the same class.
    The data is displayed in AdvancedDataGrid, which requires the children attribute. In the SQL table, I prefer one parent relation instead. Therefore my model uses both, which increases the complexity.
    My problem, I think, is that the Flex/ActionScript model is using pointers (parent), while the SQL tables uses the parentId (integer).
    How do I deal with the two different ways of referring to the parent/child? Do I need to implement both in my managed objects?
    My current implementation includes both SQL ids and AS pointers. On the result event, I create pointer relationships based on the SQL node ids. I think this may be unnecessary, as LCDS is passing the whole tree as one, to the database after my update.
    I basically unsure how to implement these parent/child relationships in ActionScript and/or SQL tables / statements. Because my current implemnations have been mucking up halfway through.
    Any hints are greatly appreciated.
    Cheers,
    Vegard

    Well, just start by making a Node class. To allow Nodes to have children, make each Node have an array (or arraylist, vector, etc.) of other Nodes.
    for example:
    class Node{
      private ArrayList<Node> children;
    }Put whatever else you need in there.
    You can then traverse these through methods you write, to return child nodes. If you need the Nodes to have knowledge of their parents, add a Node parent; variable in your Node class.
    Essentially, keep things as simple as possible, and this will allow you to write cleaner code and also decide on the depth of the structure at runtime, like you describe.

  • A bug with the new WebView??

    <font color="blue" size="2" >Hi I'm using javaFX 2.1 with Netbeans 7.2 and java 1.7.5. When trying to run this with WebView shows the error down below. The starnge thing it´s I have and old version of other code and runs without any trouble. Does anybody knows why this happens?. Thanks in advanced.</font>
    <font color="red" size="4" > Here's the code:</font>
    public class AEjemploArrays extends Application {
        private Button btn = new Button();
        private WebView web = new WebView(); //comment this and will work
        @Override
        public void start(Stage stage) {
            StackPane root = new StackPane();
            Scene scene = new Scene(root, 1200, 500);
            BorderPane bp0 = new BorderPane();
            ObservableList<String> titulos = FXCollections.observableArrayList("ArrayList", "Vector", "HashSet", "HashMap");
            ListView<String> lista = new ListView<>(titulos);
            lista.prefHeightProperty().bind(scene.heightProperty().add(-10f));
            lista.setMaxWidth(250);
            lista.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
                @Override
                public void changed(ObservableValue<? extends Number> ov, Number oldv, Number newv) {
                    System.out.println("" + newv.doubleValue());
            btn.setText("Ejecutar");
            btn.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    System.out.println("Hello World!");
            bp0.setLeft(lista);
            root.getChildren().add(bp0);
            stage.setTitle("Diversos arrays y como funcionan");
            stage.setScene(scene);
            stage.show();
        }<font color="red" size="4" > Error message:</font>
    <font color="darkblue" size="3" >ant -f C:\\Users\\ANDRES\\Documents\\NetBeansProjects\\aEjemploArrays jfxsa-run
    init:
    Deleting: C:\Users\ANDRES\Documents\NetBeansProjects\aEjemploArrays\build\built-jar.properties
    deps-jar:
    Updating property file: C:\Users\ANDRES\Documents\NetBeansProjects\aEjemploArrays\build\built-jar.properties
    Compiling 1 source file to C:\Users\ANDRES\Documents\NetBeansProjects\aEjemploArrays\build\classes
    compile:
    Detected JavaFX Ant API version 1.1
    Launching <fx:jar> task from C:\Program Files\Oracle\JavaFX 2.1 SDK\lib\ant-javafx.jar
    Launching <fx:deploy> task from C:\Program Files\Oracle\JavaFX 2.1 SDK\lib\ant-javafx.jar
    Skip jar copy to itself: aEjemploArrays.jar
    jfx-deployment:
    jar:
    run:
    Exception in Application constructor
    java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
         at java.lang.reflect.Method.invoke(Method.java:601)
         at com.javafx.main.Main.launchApp(Main.java:486)
         at com.javafx.main.Main.main(Main.java:638)
    Caused by: java.lang.RuntimeException: Unable to construct Application instance: class aejemploarrays.AEjemploArrays
         at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
         at com.sun.javafx.application.LauncherImpl.access$000(Unknown Source)
         at com.sun.javafx.application.LauncherImpl$1.run(Unknown Source)
         at java.lang.Thread.run(Thread.java:722)
    Caused by: java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
         at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
         ... 4 more
    Caused by: java.lang.IllegalStateException: Not on FX application thread; currentThread = JavaFX-Launcher
         at com.sun.javafx.tk.Toolkit.checkFxUserThread(Unknown Source)
         at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(Unknown Source)
         at com.sun.webpane.sg.prism.InvokerImpl.checkEventThread(Unknown Source)
         at com.sun.webpane.platform.WebPage.<init>(Unknown Source)
         at com.sun.webpane.sg.ImplementationManager.createPage(Unknown Source)
         at com.sun.webpane.sg.ImplementationManager.createPage(Unknown Source)
         at javafx.scene.web.WebEngine.<init>(Unknown Source)
         at javafx.scene.web.WebEngine.<init>(Unknown Source)
         at javafx.scene.web.WebView.<init>(Unknown Source)
         at aejemploarrays.AEjemploArrays.<init>(AEjemploArrays.java:29)
         ... 8 more
    Java Result: 1
    jfxsa-run:
    BUILD SUCCESSFUL (total time: 24 seconds)</font>

    Move the new WebView statement into the Start method and all will work fine.
    As the error message says, a WebView needs to be created on the FX Application thread. By trying to create the WebView where you currently are doing it, the creation attempt will be performed on the main thread.
    There is an existing Jira issue to remove the thread restriction on WebView, but it is scheduled for a later release.

  • Dynamic array

    how to implement dynamic array size in java...??
    say if i want to add the element in an array then how should i do it..??

    For dynamic array...Vector is the best one i
    est one i think....
    Sigh. Unless other code requires it (for example, JTable's DefaultTableModel),
    Arraylist is preferred over the legacy class Vector.
    And even then I wouldn't recommend ArrayList as the "best" list. What if the OP
    wanted to have a FIFO queue? Would you recommend ArrayList/Vector over
    LinkedList?

  • How to get data from php to java via xmlrpc

    I have been trying to get data from php through apache xmlrpc to java.
    I do get an value as result. The result is "Array". How how do i convert the XMLRPC Object "Array" to Java Object?
    Inside the XMLRPC "Array" Object there is object too of type Array from php.
    See code for java here
    Object result = client.execute( "blogger.getCategories", params1 );
    Code from php here
    function getCategories($appkey, $username, $password)
         global $xmlrpcerruser, $xmlrpcI4, $xmlrpcInt, $xmlrpcBoolean, $xmlrpcDouble, $xmlrpcString, $xmlrpcDateTime, $xmlrpcBase64, $xmlrpcArray, $xmlrpcStruct, $xmlrpcValue;
         $structArray = array();
         $structArray[] = new xmlrpcval(array("one" => "test"));
         return new xmlrpcresp(new xmlrpcval( $structArray , $xmlrpcArray));     
    I do get Standard String and Integer from php to Java through XMLRPC.
    Can someone help me.
    Edited by: Electron32 on Aug 13, 2010 9:44 AM

    That is what is so strange. I return an 'array' through xmlrpcval() and in Java I tried to cast it to ArrayList, Vector,String[] but get an error
    Object[] result = (Object[]) client.execute( "blogger.getCategories", params1 );
    String[] array = (String[]) result;
    Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
            at com.dirdalit.window.Main.main(Main.java:41)
    Edited by: Electron32 on Aug 13, 2010 12:25 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Parsing File

    Which is more efficient: parsing a file then store the results in an ArrayList/Vector/etc or parsing a file then puting the results in a file?
    Note:
    1. the file to be parsed is a huge log file.
    2. results will be used (stored in DB maybe).

    this is a very cool advise...i appreciate it coz i
    think am one of those guys who worries about memories
    issues too much :)
    people sometimes worry about memory too much. Youshould probably just do the easiest thing first
    (e.g., use the ArrayList, if you find it easier) and
    only worry about memory if you find that you're
    actually getting memory issues
    i'll go for saving individual results to DB during
    parsing.
    thanks again :)As an example here is where you can take full advantage of the Jav&trade;
    Let's say you decide well gee I really do want to store all the data before I add it. And right now the sets are small but one day they could get really large.
    Store the data in a List. Always make sure that except for the one line you instantiate the List (ArrayList let's say) you reference the List as a List.
    Then one day when you run into the memory size issue you could implement a simple List backed by a file of some sort (perhaps RandomAccessFile) and it will work with the rest of your code as is.
    It would obviously be slower to go on disk then from memory but it would work and be scalable. And best of all you didn't have to bust apart all your code to get there.

  • Wanna learn to implement hierarchical data structure

    I want to learn the method of handling hierarchical data in Java
    For instance if there is some kind of data which contains 6 main nodes then every node contains 2 sub nodes and there are 4 nodes under the 3rd node where as the 5th one contains two more subnodes one under another.
    So how will that be implemented?
    Ofcourse it must be possible to implement it but how can I do the same if I do not know the depth and number of nodes and will get it during the runtime?
    I had attempted to do create some thing of this kind using Turbo C++ 3.5 but after two weeks of intensive programming I was left utterly confused with innumerable pointers and pointer to pointers and pointer to a pointer to a pointers and more. At last it was me who forgot which pointer was pointing to what.

    Well, just start by making a Node class. To allow Nodes to have children, make each Node have an array (or arraylist, vector, etc.) of other Nodes.
    for example:
    class Node{
      private ArrayList<Node> children;
    }Put whatever else you need in there.
    You can then traverse these through methods you write, to return child nodes. If you need the Nodes to have knowledge of their parents, add a Node parent; variable in your Node class.
    Essentially, keep things as simple as possible, and this will allow you to write cleaner code and also decide on the depth of the structure at runtime, like you describe.

  • Parameter list in SQL native queries

    I need to migrate from Toplink 10 to EclipseLink.
    In my "old" project, I have some SQL native queries like '...... where field in #pFieldValues'
    #pFieldValues is an arraylist/vector.
    It was working perfectly with TopLink 10, but now it fails with 'Oracle Error' 'Invalid column type'.
    How can I achieve this now with EclipseLink?  (I don't want to use EJBQL queries (or JPQL queries).
    Thanks

    I made it work modifying SQL statement for Access database by passing parametres in where clause.
    But it works only for single value , though I have checked Allow multiple values: true. but fails when passing more than one value,
    Error message pops up " Failed to retrive data from database. The Microsoft Access database engine could not find the object tblHirarchy('ANSTG', 'MCIS')
    How to resolve it?
    SELECT tbl_CBP.forcast_in_MON, tbl_CBP.forcast_MON, tbl_CBP.forcast_QTR,
    tbl_Hierarchy.Technology_Group, tbl_Hierarchy.[Business_ Unit],
    tbl_Hierarchy.Product_Family, tbl_CBP.Units, tbl_CBP.Cost, tbl_CBP.REV,
    tbl_Time.Sort_order
    FROM (tbl_Hierarchy INNER JOIN tbl_CBP ON tbl_Hierarchy.Product_Family =
    tbl_CBP.PF) INNER JOIN tbl_Time ON tbl_CBP.forcast_MON =
    tbl_Time.Fiscal_Month
    where tbl_Hierarchy.Technology_Group = {?TG}
    ORDER BY [sort_order]
    union all
    SELECT [Forcast_In_MON] & ' Actuals' AS forcast_In, tbl_Time.Fiscal_Month,
    tbl_Time.Fiscal_Quarter, tbl_Hierarchy.Technology_Group, tbl_Hierarchy.
    [Business_ Unit], tbl_Hierarchy.Product_Family, tbl_Actuals.Units,
    tbl_Actuals.Cost, tbl_Actuals.REV, tbl_Time.Sort_order
    FROM (tbl_Actuals INNER JOIN tbl_Hierarchy ON tbl_Actuals.PF =
    tbl_Hierarchy.Product_Family) INNER JOIN tbl_Time ON tbl_Actuals.Actuals_MON
    = tbl_Time.Forcast_In_MON
    where tbl_Hierarchy.Technology_Group = {?TG}
    ORDER BY [sort_order];
    your HELP is highly appreciated.

  • Dynamic Component Creation

    Hi,
    Can someone tell me if there is a way to get the following code to work or another way to get the same effect? I want to be able to create buttons on demand, when the user clicks an "add" button.
    JPanel numpanel = new JPanel();
    int i;
    for(i = 1; i<13; i++){
    JButton ("num"+i) = new JButton(("Num-" + i));
    numpanel.add(("num"+i));
    }

    Do you need to hold a reference to the buttons or do yo just want to add them to the panel?
    If you just need to keep adding buttons, then use this:
    //asssume count is a class level variable
    numpanel.add(new JButton("Num-" + count++));If you need to hold a reference to each button (quite likely), then use an ArrayList/Vector to hold the buttons
    JButton b = new JButton("Num-" + count++);
    list.add(b);
    //--- list is the ArrayList that has been created and initialised.
    numpanel.add(b);When you need to retrieve any button, use list.get(i).

Maybe you are looking for

  • How to trap 1843 error. .nOT Valid month..

    This is in my cursor for loop mstart_issue := TO_CHAR(to_date(mstart_issue,'YY-MON'),'Mon.YYYY') ;                mend_issue := to_char(to_date(mend_issue,'YY-MON'),'Mon.YYYY'); But it throws 1843 error.. i Have execptions for finding value error lik

  • Dynamic selction tables and fields

    Hi Folks, I have an issue while creating program using field symbols My requirement is I need to develop a program to get table counts with respect to username and date .For that I wrote below program REPORT  ZDYNAMICFIELDS. PARAMETERS: TABNAM TYPE D

  • Include PDF file in app

    Is it possible to include a pdf file in an mobile app? If, how is it done?

  • CSS One Arm Configuration with VIP(non-shared)/IP Interface Redundancy

    With Reference to the following CCO documentation; 1). "How to Configure the CSS to Load Balance Using 1 Interface" In this example, the Real Server's (10.10.10.2 etc) gateway are pointed to the router's gateway(10.10.10.1) and used the 'add destinat

  • CRM (Abap + Java) connect with WAS (Abap + Java)

    Hello collegues, i have installed Netweaver 7.0 with Enterprise Portal. Now i must connect WAS with CRM system, but i do not what i have to connect ABAP - ABAP parts (RFC connection type TCP) or Java - Java parts (in visual admin in JCo) or ABAP - Ja