Vector and HashMap

what is the complexity of doing a vector.get(position) (vector is a Vector object) ? is it implemented like and have to proceed through the vector til position, or does it jump strigth to the point?
I have objects whose IDs are integer from 0 to n.
do I have any advantage using HashMap with ID as key or gievn this property the cost when doing get/set (get/put) operation is the same?
thanks,
pao

Yeah, people can continue to use Vector and ignore
that someone went through the trouble to create
something better and probably nothing will be
affected. I just don't think it's a good way to use a
tool. True. Though, someone also when through the trouble of making Vector compatible with the List interface. I do agree with you however.
I also don't understand why HashMap has edged
out Hashtable but people keep insisting on using
Vector over ArrayList. I haven't seen where HashMap or Vector have edged out Hashtable or ArrayList respectively. But I suspect that many of the people who learned to use the former classes simply haven't made the leap (perhaps they are not even aware that there is a leap to be made).
My main problem with Vector is
that it contains a public interface that is well
outside of the List interface. Junior developers that
are not steered away from Vector are more likely to
miss-out the List interface entirely.Agreed.
>
Also, the Java APIs are starting to show their age.
If Sun decides to make the leap and create a Java
2.0, they should clean up the JDK. If it were me,
I'd ax the Vector class. There's no need for two
array -backed list classes.True, except that it may be necessary for backwards compatibility.

Similar Messages

  • Vector and Hashmap with the same Content

    Hi Folks
    I have the following Problem, i want to set the same Content in a Vector as in an existing HashMap (both static!)
    These are my trials, both did not work.
    1.)
    static Hashmap hashMap = new HashMap();
    static Vector vector = new Vector(hashMap.values());
    2.)
    public static Vector getElements()
              HashMap cache = hashMap;
              Collection c = cache.values();
              Set set = cache.keySet();
              Iterator it = set.iterator();
              Vector cache1 = new Vector();
              while(it.hasNext())
                   String key = (String)it.next();
                   Element element = (Element)cache.get(key);
                   Element element2 = new Element();
    element2.setAttribut(element.getAttribut())
                   cache1.add(element2);
              cache = cache1;
              return cache;
    Does someone has advice??
    greetings
    Thomas

    Hi,
    why not simply make your method return the local vector (cache1) instead of using additional code ?
    By the way: I'm surprised because the method should return a Vector but instead returns a HashMap. Are you sure your code compiles ?
    Hope this helped,
    Regards.

  • Vector vs HashMap

    I have made an object firm and stored it in a HashMap with FirmId as the key. Now I have a a table with fields firm_id, code and count so in this I want to create a vector and store this table in it. Then whereever the firm_id matches in the HashMap I want to save the vector in that HashMap. Is this possible? How?

    You mean you want a name value pair where the name is firm_id and the value is an array of something (doesn't matter what it is.)
    Yes you can do that.
    You might want to consider using an actual array. Or ArrayList.

  • Problem when adding java objects in a vector and passing thru web service

    Hi! I'm getting this error when I try to add a java object I created into a vector and passing it through a web service: java.lang.IllegalArgumentException: No Serializer found to serialize a 'testObj' using encoding style 'http://schemas.xmlsoap.org/soap/encoding/'
    This does not happen when I simply add strings or Integer objects into the vector. What am I missing?
    Thanks.

    just chek this
    http://forum.java.sun.com/thread.jspa?threadID=501189&messageID=2370914
    Edited by: garava on Jul 16, 2008 1:13 PM.
    It would be great if you could paste the wsdl part for that vector and just have a look for the complex typr cntent
    like for HashMap we have the following mapping
    <complexType name="HashMap">
      <sequence>
        <element name="item" minOccurs="0" maxOccurs="unbounded">
          <complexType>
            <sequence>
              <element name="key" type="anyType" />
              <element name="value" type="anyType" />
            </sequence>
          </complexType>
        </element>
      </sequence>
    </complexType>Since in Value it should again contain a mapping for the Object which you are trying to pass then only an appropriate serializer and deserilaizer would get generated. Hope this answers your query. For refernece
    http://www.theserverside.com/tt/articles/article.tss?l=Systinet-web-services-part-2
    [http://www.theserverside.com/tt/articles/article.tss?l=Systinet-web-services-part-2|For refernce tutorial]
    Thanks,
    Avadhoot Sawant.
    Edited by: garava on Jul 16, 2008 1:16 PM

  • Vector() and maybe List of Vector() ?

    Is there a java class that creates automatically a list (list,array,or vector) of vector()?
    Thank you for your help.

    I just need to save fields of a graphic interface into a vector and then insert the vector to a list or >something else.
    Do you thing it is a good way to programm if i create an array of vector?To know which is the best data structure for your propose you must have a good knowledge about your problem. You may know your problem, but I don't.
    Choosing a right data structucture will improve the performance of your aplication, plus make the code simpler, the oposite will have oposite results.
    If, for example, big amoust of data will be stored and the need to be procesed in any orther, ArrayList may be a good solution, but if they mus be processed in a specifical order, and no the same order they were added to the ArrayList, this data structure will spoil amazingly the peroformace of your aplication (it happen to me), while HashTable, or HashMap if no synchronization is required, will increase notably your performace.
    Which data struture you should employ?. You known your problem, spend a couple of hours understandind the coollection framework as I'm sure you'll fin a suitable structure which even may save you the tieme you spend undestandind the collection framework by making the code easier.
    Abraham.

  • Difference  between null vector and empty Vector

    What is the diffrence between null vector and empty vector.

    null vector means the JVM doesn't allocate memory.It doesn't exist
    in memory. NO instance!
    empty vector means the JVM allocated memory.It exists in memory.
    it's a instance than is accessabel.But only have on elements.
    GL&HF.

  • Iterating performance: ArrayList, LinkedList, and Hashmap for N 1,000,000

    I have seen some websites discussing about the performance of ArrayLists, LinkedLists, and Hashmaps:
    http://forum.java.sun.com/thread.jspa?threadID=442985
    http://java.sun.com/developer/JDCTechTips/2002/tt0910.html
    http://www.javaspecialists.co.za/archive/Issue111.html
    http://joust.kano.net/weblog/archives/000066.html
    If I understand it right an ArrayList in general is faster for accessing a particular element in the collection and I can't find some pro's of using a LinkedList.
    My question is: If I only use a large collection with more than 1 million elements for iterating from begin to end (i.e. for loop), is it faster to use a linked list or a custom linked list instead of an arraylist (or hashmap)? Since you can iterate "directly" through a (custom) linked list, which is not possible with a arraylist?
    Edited by: 9squared on Nov 23, 2007 1:48 PM

    Thanks for the help, I wrote some code and tested it
    import java.util.ArrayList;
    import java.util.List;
    import java.util.LinkedList;
    public class TestTemp {
         public static void main(String[] args) {
              List<Node> a = new ArrayList<Node>();
              Node b = new Node("a");
              String[] c = new String[10000000];
              Node temp = b;
              for (int i = 0; i < 10000000; i++)
                   a.add(new Node("a"));
                   temp.next = new Node("b");
                   temp = temp.next;     
                   c[i] = "c";
              long tstart;
              tstart = System.currentTimeMillis();
              for (int i = 0; i < 10000000; i++)
                   c[i] = "cc";
                   if (i%200000 == 0)
                        System.out.println("Array " + i + ": " + (System.currentTimeMillis()-tstart));
              tstart = System.currentTimeMillis();
              temp = b;
              for (int i = 0; i < 10000000; i++)
                   temp.next.text = "bb";
                   temp = temp.next;
                   if (i%200000 == 0)
                        System.out.println("LinkedList " + i + ": " + (System.currentTimeMillis()-tstart));
              tstart = System.currentTimeMillis();
              for (int i = 0; i < 10000000; i++)
                   a.get(i).text = "aa";
                   if (i%200000 == 0)
                        System.out.println("ArrayList " + i + ": " + (System.currentTimeMillis()-tstart));
    public class Node {
         public String text;
         public Node next;
         public Node(String text)
              this.text = text;
    }Here are some results in milliseconds, and indeed just iterating doesn't take very long
    Elements     Linked     Arraylist     Array
    200000     0     0     1
    400000     5     13     5
    600000     9     22     9
    800000     14     32     12
    1000000     20     42     16
    1200000     25     52     19
    1400000     31     63     23
    1600000     37     72     26
    1800000     42     82     30
    2000000     47     92     33
    2200000     51     101     37
    2400000     56     112     40
    2600000     60     123     44
    2800000     65     134     47
    3000000     69     143     51
    3200000     73     152     55
    3400000     78     162     59
    3600000     84     175     63
    3800000     103     185     67
    4000000     108     195     70
    4200000     113     207     74
    4400000     117     216     78
    4600000     122     225     81
    4800000     127     237     85
    5000000     131     247     88
    5200000     136     256     92
    5400000     142     266     97
    5600000     147     275     101
    5800000     153     286     107
    6000000     159     298     113
    6200000     162     307     117
    6400000     167     317     121
    6600000     171     326     125
    6800000     175     335     128
    7000000     180     346     132
    7200000     184     358     136
    7400000     188     368     139
    7600000     193     377     143
    7800000     197     388     147
    8000000     201     397     150
    8200000     207     410     154
    8400000     212     423     157
    8600000     217     432     162
    8800000     222     442     167
    9000000     227     452     171
    9200000     231     462     175
    9400000     236     473     178
    9600000     242     483     182
    9800000     249     495     185
    10000000     257     505     189

  • Please help, 2D Array of Vectors and Incompatible types :(

    I have a 2D array of vectors called nodeLocations but when I try and access the vector inside I get a compile error.
    My code is something like this:
    nodeLocations[j].addElement(noArc)
    My editor picks up that its a Vector and shows me addElement as an acceptable entry to put after the "." yet the compiler says:
    "addElement(java.lang.Object) in java.util.Vector cannot be applied to (int)"
    Can someone please help?
    Thank you in advance.
    also a related problem:
    I get inconvertible types (says int required) when I try and get an element from a vector stored in a 2D Array. I know that it comes out as an object and so should be cast but it does not seem to work. My code is as follows:
    else if (((int)(nodeLocations[nodeNumber][adjNodeNumber].elementAt(0))) != distance)
    I would appreciate any help anyone can give.
    Similar errors to the above two happen when
    I try a push with a Stack in a vector.
    I try to get something out of the stack inside the vector.

    The Vector class's addElement() method requires an Object parameter. It appears that you're trying to add an int to the Vector. You'll need to create an Integer object and place that into the vector (see sample below) or use the pre-release version of JDK 1.5 which provides autoboxing capabilities.
    int z = 5;
    Integer x = new Integer(z);
    nodeLocations[j].addElement(x);

  • Returning vector and null pointer exception

    Hi, I'm writing a mailing program which so far is working fine, but I have now run into a problem which is completely throwing me. My mailer needs to be able to load multiple attachments - and also to be able to deal with an HTML text which contains multiple images. In each case, what I'm trying to do is to put the attachments and the images into separate vectors and process them through an iterator. The logic, at least, I hope is correct.
    I can get my code to compile but it keeps throwing a null pointer exception a runtime. Somehow, I just can't get it to pass the vector from one part of the code to another.
    Can anyone help me? I've tried various things, none of which seem to work. My code, as it stands, is posted in a skeletal form below.
    Thanks for any ideas:
    public class MailSender
       // declare various variables, including:   
         Vector embeddedImages;
         String HTMLString;
        public MailSender()
            setup();
        private void setup()
         //this part of the program sets up the various parts of the mail  (to, from, body etc)    
          HTMLString = "blah blah blah";  //sample HTMLString   
           Vector embeddedImages = null; //is this correct?
            if (HTMLString.length() > 0)
                processHTMLString(HTMLString);
         private String procesHTMLString(String htmlText)
            Vector embeddedImages = new Vector(); // I construct my vector here, is this correct?
            //Here I process the HTML string to extract the images
            //get the file path of the image and pass it to the vector
            addToVector(imageFile);
            return HTMLString;
        public Vector addToVector(String imageFile)
            embeddedImages.add(imageFile);
            return embeddedImages;
        private void send()
            //this part does the sending of the mail
            //at some part in this method I need to get at the contents of the vector:
            //but this part isn't working, I keep getting a null pointer exception
            Iterator singleImage = embeddedImages.iterator();
            while (singleImage.hasNext())
        public static void main(String[] args)
            MailSender ms = new MailSender();
            ms.send();
            System.out.println("MailSender is done ");
    }

    >>>>while they don't have a clue on how the language and/or programming in general works.
    Thank you, salpeter, for your esteemed estimation of my programming competence.
    >>>What I'm wondering is: how come people always start building applications... blah blah
    The reason being, is that it happens to be my job.
    OK, I'm perhaps slower than most and there are things I don't yet understand but I get paid probably about a tenth of what you do (and maybe even less). I regard it as a kind of apprenticeship which, after a past life having spent twenty years packing crates in a warehouse, is worth the sacrifice. Six months ago I'd never written a line of code in my life and everything I've learned since has been from books, the good people in these forums, and a lot of patient trial and error. It's hard work, but I'll get there.
    I say this, only as encouragement to anyone else who is trying to learn java and hasn't had the benefit of IT training at school and a four year computing course at university paid for by the parents, and for whom the prohibitive cost (in both time and money) of most java courses would never allow them to get on this ladder.
    Excuse my somewhat acerbic posting, but comments such as yours tend to provoke...
    Thank you EverNewJoy for explaining this to me. I haven't had time yet to try it out, but at least the concept now is clear to me.

  • Jax-ws 2.1 - problems returning hashtable and hashmap

    Hi,
    We're developing a set of applications that communicate via web services.
    The company decided that to do this we should use jax-ws 2.1.
    Everything is going ok, its really easy to use, except for a web method that returns a java.util.Hashtable.
    In the endpoint there's no problem, it compiles and deploys to a tomcat 5.5 without a problem.
    The client can access the wsdl via url, download it and create the necessary files (we use netbeans 5.5 for this).
    We can invoke the method getConfig without a problem, but the object returned only has the java.lang.Object 's methods, not the java.util.Hastable 's .
    Endpoint:
    package xxx.cdc_pm_i;
    import java.util.Hashtable;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import javax.xml.bind.annotation.*;
    @WebService()
    public class cdc_pm_i{
    @WebMethod
    public Hashtable getConfig() {
    Hashtable<String,String> config = new Hashtable<String,String>();
         config.put("1","1");
         config.put("2","2");
    return config;
    Client:
    try { // Call Web Service Operation
    xxx.CdcPmIService service = new xxx.cdc_pm_i.CdcPmIService();
    xxx.cdc_pm_i.CdcPmI port = service.getCdcPmIPort();
    // TODO process result here
    xxx.cdc_pm_i.Hashtable result = port.getConfig();
    } catch (Exception ex) {
         ex.printStackTrace();
    I'm fairly unexperienced in Web Services and i have no idea why this works for any kind of return object (as long as its serializable) and has this problem with hashtables and hashmaps.
    Any idea on how to solve this?
    Thanks in advance,
    Rui

    Didn't find the solution for this, but any object that contains an Object in its methods / attributes had the same problems, so i just built my own table that only supports Strings and the problem was solved.
    If anyone knows why i had this problem and wants to share a solution, please do so.

  • Vector and Jtree 4Duke

    hi
    i am having poblem with my jtree as i am not able to show the object in my vector as a different node
    {each object is node of my tree}
    unfortunately they all appear flat in the root, and in sequence{as one node} ??
    i have done everything but still no answer??
    thanks in advance for any solution
    public class Gui extends JFrame
    {  Vector root = new Vector();
    public JTree theTree ;
    public SERGui( )
    System.out.println(root.size());//root vector is empty
    roott = new DefaultMutableTreeNode (root);
    model = new DefaultTreeModel (roott) ;
    theTree = new JTree (model);      
    public Vector addOne(String newString)
    if (!root.contains(getQuery))
               root.add(newString);
    model.reload();
    // //updateTree(); i also try this method whiich does not work
    return root;
    public void updateTree(){
    DefaultMutableTreeNode v = (DefaultMutableTreeNode)theTree.getModel().getRoot();
    for(int i=0;i<root.size();i++)
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode)root.elementAt(i);
                   roott.add(node);
    ((DefaultTreeModel)theTree.getModel()).reload(v);
    //DefaultMutableTreeNode node = null;
    print_vector(root);
      //root.clear();
         }and my other class
    where i call this methos is as follow
    Class Search()
    public void countWord(String newString)
    {Gui.addOne(newString);
    }}

    You are passing a Vector into the constructor of the DefaultMutableTreeNode to create the root of your tree. The DefaultMutableTreeNode will use this object's string representation (by calling toString on whatever object you pass in its constructor) as the name of the tree node. So basically you will see the entire contents of the vector as the name of your root node.
    You need to traverse your vector, and use each element to create a DefaultMutableTreeNode and add it to your root node.
    here is the modified code
    public class Gui extends JFrame {
    private Vector rootVector = new Vector();
    private JTree theTree;
    private DefaultMutableTreeNode rootNode;
    private DefaultTreeModel model;
    public Gui() {
    System.out.println(rootVector.size());
    //root vector is empty
    rootNode = new DefaultMutableTreeNode("Root");
    model = new DefaultTreeModel(rootNode);
    theTree = new JTree(model);
    public Vector addOne(String newString) {
    if (!rootVector.contains(newString)) {
    rootVector.add(newString);
    updateTree();
    return rootVector;
    public void updateTree() {
    rootNode.removeAllChildren();
    for (int i = 0; i < rootVector.size(); i++) {
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(
    rootVector.elementAt(i));
    rootNode.add(node);
    ((DefaultTreeModel) theTree.getModel()).reload(rootNode);
    Hemant Mahidhara

  • 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!

  • How to store data from textfile to vector and delete a selected row.

    Can someone teach me how to store data from textfile to vector and delete a selected row. And after deleting, i want to write the changes in my textfile.
    Do someone has an idea? :)

    nemesisjava wrote:
    Can someone teach me how to store data from textfile to vector and delete a selected row. And after deleting, i want to write the changes in my textfile.
    Do someone has an idea? :)What's the problem? What have you done so far? What failed?
    What you described should be pretty easy to do.

  • Merging a set and hashmap

    Hi Guys,
    I have a set in which I store some unique userdefined objects,say a "Color" object.
    So my collection set will look as follows:
    set<Color> objects.
    For example:-
    (color1)
    (color2)
    (color3)
    (color4)
    (color5)
    (color6)
    (color7)
    (color8)
    (color9)
    (color10)
    I also have a HashMap which stores objects as follows:
    HashMap<Color,Color> objects(Also userdefined "Color" objects).
    For example:-
    (color1,color20)
    (color2,color21)
    (color3,color22)
    (color4,color23)
    (color4,color24)
    (color5,color25)
    My need is that I want to merge this set and hashmap so that the resulting collection looks as follows:
    (color1,color20)
    (color2,color21)
    (color3,color22)
    (color4,color23)
    (color4,color24)
    (color5,color25)
    (color6,null)
    (color7,null)
    (color8,null)
    (color9,null)
    (color10,null)
    How could this be achieved.
    Any help is appreciated.
    Thanks....
    P

    Hi,
    I do not understand what problem you are actually facing: if you manage to have your map of five items, then creating a map of ten items should be no problem.
    Bye.

  • Vector and my object??

    hi all,
    I am reading a binary file, then creating the object and adding that object in my vector. How can i get it back according to its id? let is say i added all the customers read from file and now i want to get customer 3?
    int thisId=dis.readInt();
    String thisName=dis.readUTF();
    double thisBalance=dis.readDouble();
    Customer cus=new Customer(thisName,thisId,thisBalance);
    cusList.add(cus);
    abdul

    Best possible way is to use Hashtable and put customerid as key and Customer object
    as value.
    Modify your code with,
    Customer cus=new Customer(thisName,thisId,thisBalance);
    some-hashtable-object.put(thisId,cus);
    now if you want to take particular Customer
    use
    Customer c = (Customer)some-hashtable-object.get(any customerid);
    Now if you don't want to use Hashtable and continue with Vector then you have to iterate the,
    Vector and whether object has id 3 .
    like
    for(int i=0;i<Vectorobject.size();i++){
    Customer c = (Customer) Vectorobject.get(i);
    id = c.getCustomerId() // or any method you have to get id;
    // check it....
    But i think Hashtable is the better way to use here.
    I think you understand what i want to say .
    Tarak.

Maybe you are looking for

  • I NEED HELP!! my iphone 5s wont activate after updating to ios 8 . what is wrong?

    hello! I updated to ios 8 two days ago and it was ok. I started using my iphone later that day and it just rebooted . Now it wont activate .

  • b Urgent.Doubt in Scripts regarding itcsy.

    Hi All, I have the requirement to modify the Standard Script (F140_ACC_STAT_01) and Print Program name is (RFKORD10) to add three fields  at item level to display to print <b>Due Date ,Past Due and PO# number </b>.for these fields i am using <b>RF140

  • ICal Helper Crashing (Snow Leopard 10.6.2)

    I no longer get iCal alarm notifications on my desktop. I believe it's because iCal Helper keeps crashing (log example at the end of this message). I've tried deleting iCal caches, preferences, et al. to no avail. I really hope that it's not caused b

  • In PO condition pricing date

    Dear experts How to change manually condition pricing date in PO item level regards vijju

  • Reverse document for check voided with FCH9

    I voided a manual check that was created by using FCH9. I want to be able to reverse the document, but when I tried to reverse, I got an error that the document was already cleared and could not be reversed. Is there a way to reverse the payment docu