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.

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 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.

  • Vector is way faster than HashMap (why?)

    I thought that HashMap would be faster than Vector (in adding stuff) ... could anyone explain to me why there was such a HUGE difference??
    here's the code I used:
    public class SpeedTest
    public static void main(String[] args)
       final int max=1000001;
       Integer[] arrayzinho = new Integer[max];
       Arrays.fill(arrayzinho,0,max,new Integer(1));
       Vector jota = new Vector(max,max);
       HashMap ele = new HashMap(max,1);
       System.out.println("Adicionando " + (max-1) + " elementos ao array...");
       long tempo = System.currentTimeMillis();
       for(int i=0;i<max;i++)
          arrayzinho[i] = new Integer(i);
       System.out.println("A opera??o demorou " + ((System.currentTimeMillis()-tempo)) + " msecs.");
    //ops
       System.out.println("Adicionando " + (max-1) + " elementos ao Vector...");
       tempo = System.currentTimeMillis();
       for(int i=0;i<max;i++)
          jota.add(arrayzinho);
    System.out.println("A opera??o demorou " + ((System.currentTimeMillis()-tempo)) + " msecs.");
    //ops
    System.out.println("Adicionando " + (max-1) + " elementos ao HashMap...");
    tempo = System.currentTimeMillis();
    for(int i=0;i<max;i++)
    ele.put(arrayzinho[i],arrayzinho[i]);
    System.out.println("A opera??o demorou " + ((System.currentTimeMillis()-tempo)) + " msecs.");
    Of course, when adding to HashMap, two values are entered instead of just the one added in the Vector... But, even doubling the time Vector used, the difference is huge!
    here's some output I've got:
    1:
    Adicionando 1000000 elementos ao array...
    A opera??o demorou 4500 msecs.
    Adicionando 1000000 elementos ao Vector...
    A opera??o demorou 469 msecs.
    Adicionando 1000000 elementos ao HashMap...
    A opera??o demorou 7906 msecs.
    2:
    Adicionando 1000000 elementos ao array...
    A opera??o demorou 4485 msecs.
    Adicionando 1000000 elementos ao Vector...
    A opera??o demorou 484 msecs.
    Adicionando 1000000 elementos ao HashMap...
    A opera??o demorou 7891 msecs.
    and so on, the results are almost the same everytime it's run. Does anyone know why?

    Note: This only times the for loop and insert into each one... not the lookup time and array stuff of the original..
    Test One:
    Uninitialized capacity for Vector and HashMap
    import java.util.*;
    public class SpeedTest
        public static void main(String[] args)
            final int max = 1000001;
            Vector jota = new Vector(); // new Vector(max,max);
            HashMap ele = new HashMap(); // new HashMap(max,1);
            Integer a = new Integer(1);
            long tempo = System.currentTimeMillis();
            for (int i = 0; i < max; ++i)
                jota.add(a);
            long done = System.currentTimeMillis();
            System.out.println("Vector Time " + (done - tempo) + " msecs.");
            tempo = System.currentTimeMillis();
            for (int i = 0; i < max; ++i)
                ele.put(a, a);
            done = System.currentTimeMillis();
            System.out.println("Map Time " + (done-tempo) + " msecs.");
        } // main
    } // SpeedTestAdministrator@WACO //c
    $ java SpeedTest
    Vector Time 331 msecs.
    Map Time 90 msecs.
    Test Two:
    Initialize the Vector and HashMap capacity
    import java.util.*;
    public class SpeedTest
        public static void main(String[] args)
            final int max = 1000001;
            Vector jota = new Vector(max,max);
            HashMap ele = new HashMap(max,1);
            Integer a = new Integer(1);
            long tempo = System.currentTimeMillis();
            for (int i = 0; i < max; ++i)
                jota.add(a);
            long done = System.currentTimeMillis();
            System.out.println("Vector Time " + (done - tempo) + " msecs.");
            tempo = System.currentTimeMillis();
            for (int i = 0; i < max; ++i)
                ele.put(a, a);
            done = System.currentTimeMillis();
            System.out.println("Map Time " + (done-tempo) + " msecs.");
        } // main
    } // SpeedTestAdministrator@WACO //c
    $ java SpeedTest
    Vector Time 60 msecs.
    Map Time 90 msecs.
    We see that IF you know the capacity of the vector before its usage, it is BEST to create one of the needed capacity...

  • Chosing from Vectors, HashMaps or Arrays

    Hi All,
    I have to decide on which of these to use for my problem. I want a Collection that holds values like
    [Name, year of Birth]
    ["Tom", 1952]
    ["Dick", 1972]
    ["Harry", 1992]
    .where the first element is a String type and its related element is an integer ...
    the age old solution looks like using a 2-D array ... but in my case the list has to expand vertically and it could be possible that I have more data values laterally as well like "Age" field added up
    ["Tom",  1952, 53, ...... ]
    .I am not able to make up my mind as to chosing between Vectors or Hashmaps or Lists for this situation .... I want to avoid usng a n-D array and instead use some of the features offered by Java ...
    since I am relatively new to Java ... please explain why one should use a vector or a hashmap for this

    1. Definitely not Vector, unless you need synchronization. Use ArrayList instead.
    If your key is always the name, and the person may have many attributes, create a person class.
    class Person
       String name;
       int YearOfBirth;
       String phoneNumber;
       //whatever 
    }Put them in a HashMap with keys of name, and values of Person. Then if you want to add more attributes to Person, it is easy--your HashMap data structure won't change.
    Map map = new HashMap();
    map.put("Tom", new Person("Tom", 1952, "555-555-5555"));
    //or, maybe better, so name isn't duplicated incorrectly:
    Person person = new Person("Tom", 1952, "555-555-5555"));
    map.put(person.getName(), person);

  • Integer in Vector

    i have Class a which includes a Vector.
    i call a method in that Class a from Class b, which helps to pass an integer to the Vector.
    this is the Code:
    private integerVector Children = new Vector();
    public void addChild (int child)
    {Children.add( new integer(2));  } // Add child
    Any mistakes?
    thx

    The Java collections(Vector, ArrayList, HashMap and so on) store object references - not primitive values. Your compiler is telling you that there is no method of the Vector class called add that takes an int parameter. You need to wrap your integer in it's wrapper class, Integer before you add it to your vector as:
    public void addChild (int child)
    { Children.add( new Integer(child)); } // Add childGood luck to you
    Lee

  • Hashmap's empty

    Hi dudes
    I start at the beginning^^
    I'm quite new in java and I have to write an application as a practice in java, which analyses txt files in a lot of zip files about their DayLightSaving handling (^^) . There are 4 types of txt files ... (ceva.txt / ice.txt / ...) and I have for each type a seperate button/method... I have a method which goes through all Zip Files and reads out the txt files and store them in a Vector of ZipEntries and returns it.
    an other class (the GUI class) will get this information for editing... So if i want to reaccess these txt files I have to create a new stream for the zip files because the zipentries don't know from which file it comes^^ .
    So for this I made a HashMap with the entries <ZipEntry, String (pathOfZipFile)>
    this map will be filled when the application reads out the zip files at the first time. The hashmap fill in works ( saw it in debug mode ) but as soon as the process stops and the GUI will be visible again the Hashmap is lost.
    Does anybody know why this happens or another/better way to do what I want to do?
    I hope u can understand what I wrote^^

    By the way, am I missing something with the pairs of carets (^^) all over the >place? Is this a new lingo the kids are using nowadays? :)I use this as an emoticon :) but you can ignore it anyway
    I hope this part is useful , thank you for the quick response
         private HashMap<ZipEntry, String> hashmapEntryZip; //declaration of the Hashmap
         public AnalyserCore()
              mainZipDir = new File(AnalyserGUI.ZIP_DIR);
              zipFileList = mainZipDir.listFiles();          
              hashmapEntryZip = new HashMap<ZipEntry, String>();
            /** Method which reads out the zips and stores the txt's in the vector and hashmap*/
         public Vector<ZipEntry> analyzeData(String mode)
              //StringBuffer tempBuffer = new StringBuffer();     //AnalyseArea Output         // buffered buffer^^ for temporarly saving the data ...
              //StringBuffer textBuffer = new StringBuffer();     //temp File Output               //... and write it to this buffer
              Long dateBevor = Calendar.getInstance().getTimeInMillis(); //(start time) for time used statistics
              Vector<ZipEntry> fileArray = new Vector<ZipEntry>();
              ZipEntry entry ;
              fileTemporaryOutput = new File("ch/schann/analyse/" + mode + ".txt");
              try
                   fileTemporaryOutput.createNewFile(); //Create the temporary File
                   //FileWriter writer = new FileWriter(fileTemporaryOutput);               
                   for ( int p = 0; p < zipFileList.length; p++ )
                        String str = new String();
                        str += "\n[ zip ] File: " + (p+1) + "(" + zipFileList[p].getName() + ") ...\n";
                        str += "-------------------------\n";
                        // File reading whithin the Zipfile
                        zipReading = new ZipInputStream(new FileInputStream(zipFileList[p]));
                        entry = zipReading.getNextEntry();
                        int fileIndex = 0;
                        while (entry != null)
                             String filePath = entry.getName();
                             int lastSlashPos = filePath.lastIndexOf("\\");
                             String fileName = filePath.substring(lastSlashPos + 1);
                             String meterReadout = fileName.substring(0, 2);
                             if (meterReadout.equalsIgnoreCase(mode))
                                  fileIndex++;
                                  fileArray.add(entry);
                                  this.hashmapEntryZip.put(entry, zipFileList[p].getAbsolutePath());
                                  str += "[ txt ]File " + fileIndex + ":" + filePath + "...\n";
                             entry = zipReading.getNextEntry();
                        str += "[* NO MORE ELEMENTS *]\n";
                        //writer.write(str);
                        //writer.flush();
                        System.out.println(str);
                        zipReading.close();
                   Long dateAfter = Calendar.getInstance().getTimeInMillis();//(end time) for time used statistics
                   System.out.println("Time Used: " + (dateAfter - dateBevor) + "ms");
              catch(Exception e)
                   System.out.println("\n--------------\n" + e.getMessage());
                   e.printStackTrace();
              /*catch(FileNotFoundException ex)
                   System.out.println("[File Not Found:] " + ex.getMessage());
              catch ( IOException e)
                   System.out.println("[IO -ERROR:] " + e.getMessage());
              return fileArray;
         }

  • How to expand a JTree depending on a property

    Hi I have a JTree that needs to be expandAll if a property in the ini file is true. Can some tell me how I can do it or give me an example. If needed i can post my code. Here the addtreeDisplays() has to expandAll depending on a string(true ).
    Can some help me out.
    Thanks,
    public class TreeDisplayPanel extends JPanel implements QMRequestListener,
                                                            TopologySelectionListener,
                                                                          PropertyChangeListener
        /** Creates new TreeDisplayPanel */
        //Key to get from property file
        String _treeKey = "tree.display.type";
        //default display
        public final static int TREE_DISPLAY = 0;
        public final static int STAR_DISPLAY = 1;
        public final static int BOTH_DISPLAY =2;
         Properties _displayProp = null;
        //Main panel where everything gets put on to be displayed
        public JPanel _mainDisplayPanel;
        //current default display
        private int treeDisplayPreference = STAR_DISPLAY;
        private MQETabbedPane _treeTabPane;
        private MQETabbedPane _viewTabPane;
        private String treeDisplayTitle;
         static private final String treeviewKey = "tree.view.text";
         static private final String starviewKey = "star.view.text";
         static private final String splitviewKey = "split.view.text";
         static private final String mergeviewKey = "merge.view.text";
         // Default tree displays.
         private HyperbolicTreePanel hyperbolicTreePanel = null;
         private NavigatorTreePanel navigatorTreePanel = null;
         // A store for any queue manager tree displays created
         // by the user. This will enable these trees to be
         // modified whenever the user invokes a expand/collapse
         // all action on a node or whenever the user changes
         // the leaf node expansion preference.
         private Vector<NavigatorTreePanel> qmgrTreeDisplays =
            new Vector<NavigatorTreePanel>();
         //HashMap of indexes correspond to indexes in tabbed paned that are merged, it contains
        //hashtables of components in those merged indexes
        HashMap _qmMergedIndexes = new HashMap();
        //Current listeners to this panel on node selections
        protected Vector<TopologySelectionListener> _tsListeners =
            new Vector<TopologySelectionListener>();
         private TopologyModel m_model = null;
         private TopologyModelNode m_nnode = null;
         private TopologyDisplayPanel tdp = null;
        public TreeDisplayPanel(TopologyModel model, Properties prop, String displayTitle) {
            super(new BorderLayout());
              m_model = model;
              _displayProp = prop;
              treeDisplayTitle = displayTitle;
            initComponent();
            initGui();
        private void initComponent()
              _mainDisplayPanel = ComponentFactory.getInstance().createTitledPanel(treeDisplayTitle);
              _mainDisplayPanel.setLayout(new BorderLayout());
              add(_mainDisplayPanel, BorderLayout.CENTER);
        private void initGui()
            if (_displayProp != null)
                   // Get the current display preference.
                   String defaultDisplay = Integer.toString(STAR_DISPLAY);
                treeDisplayPreference = Integer.parseInt(_displayProp.getProperty(_treeKey, defaultDisplay));
            try
                //Add according to your display property
                _treeTabPane = new MQETabbedPane();
                _viewTabPane = new MQETabbedPane(JTabbedPane.BOTTOM);
                _viewTabPane.addMouseListener(new MouseListener()
                    public void mouseClicked(MouseEvent e)
                        final int tabNum = _viewTabPane.getUI().tabForCoordinate(_viewTabPane,e.getX(),e.getY());
                        //Only if the mouse click is a right mouse and tab number is not on overview pane or doc pane is the popup valid
                        if (SwingUtilities.isRightMouseButton(e) && tabNum > 1)
                            final String tabStr = _viewTabPane.getTitleAt(tabNum);
                            JPopupMenu popup = new JPopupMenu();
                            JMenuItem menuItem1 = new JMenuItem(new AbstractAction("Close " + tabStr)
                                public void actionPerformed(ActionEvent e)
                                    //Remove it from our HashMap of merged panes if it exists
                                    if (_qmMergedIndexes.containsKey(tabStr))
                                        _qmMergedIndexes.remove(tabStr);
                                            // Remove the Qmgr tree display.
                                            NavigatorTreePanel treePanel = (NavigatorTreePanel)_viewTabPane.getComponentAt(tabNum);
                                            ExpandingModelNode model = (ExpandingModelNode)treePanel.getNavigatorTreeModel();
                                            model.getNode().removeTreeModelListener(model);
                                            qmgrTreeDisplays.remove(treePanel);
                                    _viewTabPane.removeTabAt(tabNum);
                                  String mergeview = StringFactory.getString(mergeviewKey);
                            JMenu merge = new JMenu(mergeview);
                            merge.setEnabled(false);
                            int numTabs = _viewTabPane.getTabCount();
                            //System.out.println("Num of tabs " + numTabs);
                            //Only allow merging if you have more then 2 panes (1 - Overview, 2 - Qmgr, 3-Qmgr....
                            //Also if the current pane is not a merge pane already
                            if (numTabs > 3 && !_qmMergedIndexes.containsKey(tabStr))
                                //Do not enable this menu if the number of already merged Indexes - the number of tabs
                                //is greater then two (One Valid pane + Overview pane). The reason is because then there is
                                //no valid pane to merge with
                                if ((numTabs - _qmMergedIndexes.size()) > 3)
                                    merge.setEnabled(true);
                                    for (int i = 2; i<numTabs; i++)
                                        //Add only valid tabs and not already merged tabs
                                        if (i != tabNum && !_qmMergedIndexes.containsKey(_viewTabPane.getTitleAt(i)))
                                            //JMenuItem mergeItem = new JMenuItem(new AbstractAction(_viewTabPane.getTitleAt(i))
                                                      JMenuItem mergeItem = new JMenuItem(new AbstractAction(_viewTabPane.getToolTipTextAt(i))
                                                public void actionPerformed(ActionEvent e)
                                                    try
                                                        //System.out.println("Action Name for " + e.getActionCommand());
                                                        //Work around for java bug in JTabbedPane
                                                        _viewTabPane.setSelectedIndex(0);
                                                        _viewTabPane.validate();
                                                        //End workaround
                                                        //Strip off the fully qualified name to contain only the name of the QM name
                                                                     String mergeTabName = m_model.getQMgrName(e.getActionCommand());
                                                                     JPanel splitPanel = new JPanel(new BorderLayout());
                                                        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
                                                        splitPane.setBorder(null);
                                                        splitPane.setOneTouchExpandable(true);
                                                        int mergeTabIndex =  _viewTabPane.indexOfTab(mergeTabName);
                                                        String mergeTabString = _viewTabPane.getTitleAt(mergeTabIndex);
                                                                     Component mergeComp = _viewTabPane.getComponentAt(mergeTabIndex);
                                                        String mergeCompAddress = _viewTabPane.getToolTipTextAt(mergeTabIndex);
                                                                     splitPane.setLeftComponent(mergeComp);
                                                                     int currentTabIndex =  _viewTabPane.indexOfTab(tabStr);
                                                        Component currentComp = _viewTabPane.getComponentAt(currentTabIndex);
                                                                     String currentCompAddress = _viewTabPane.getToolTipTextAt(currentTabIndex);
                                                        splitPane.setRightComponent(currentComp);
                                                        splitPanel.add(splitPane, BorderLayout.CENTER);
                                                        String mergeName = mergeTabName + "/" + tabStr;
                                                                     String toolTipName = mergeCompAddress + " | " + currentCompAddress;
                                                        //_viewTabPane.addTab(mergeName, splitPanel);
                                                                     addTabToDisplay(mergeName, toolTipName, splitPanel);
                                                        splitPane.setDividerLocation(.5);
                                                        int mergeIndex = _viewTabPane.indexOfTab(mergeName);
                                                                      if (mergeIndex != -1)
                                                            //_viewTabPane.setToolTipTextAt(mergeIndex, mergeName);
                                                                          //_viewTabPane.setSelectedIndex(mergeIndex);
                                                            //Now lets update our ongoing vector/hashmap
                                                            //Create a hash map with the current merged view
                                                            Hashtable mergeViews = new Hashtable();
                                                            mergeViews.put(mergeCompAddress,mergeComp);
                                                            mergeViews.put(currentCompAddress,currentComp);
                                                            _qmMergedIndexes.put(mergeName, mergeViews);
                                                    catch (Exception ex)
                                                        ex.printStackTrace();
                                            merge.add(mergeItem);
                                  String splitKey = StringFactory.getString(splitviewKey);
                            JMenu splitMenu = new JMenu(splitKey);
                            splitMenu.setEnabled(false);
                            //Only allow to split if the current tab has a merged view
                            if (_qmMergedIndexes.containsKey(tabStr))
                                splitMenu.setEnabled(true);
                                Hashtable mergeHash = (Hashtable)_qmMergedIndexes.get(tabStr);
                                Enumeration enumeration = mergeHash.keys();
                                while (enumeration.hasMoreElements())
                                    //Create a new menu item for each QM in View
                                    String node = (String)enumeration.nextElement();
                                    JMenuItem mergeItem = new JMenuItem(new AbstractAction(node)
                                        public void actionPerformed(ActionEvent e)
                                            //Work around for java bug in JTabbedPane
                                            _viewTabPane.setSelectedIndex(0);
                                            _viewTabPane.validate();
                                            //End workaround
                                            String splitTabName = e.getActionCommand();
                                            //Get the merge hash for this tab num
                                            Hashtable splitHash = (Hashtable)_qmMergedIndexes.get(tabStr);
                                            Enumeration enumeration = splitHash.keys();
                                            _viewTabPane.removeTabAt(tabNum);
                                                      int iIndexOfSplit = 0;
                                            while (enumeration.hasMoreElements())
                                                //Add new pane for the views in the hashtable
                                                String nodeAddress = (String)enumeration.nextElement();
                                                           String nodeName = m_model.getQMgrName(nodeAddress);
                                                           NavigatorTreePanel currentComp = (NavigatorTreePanel)splitHash.get(nodeAddress);
                                                addTabToDisplay(nodeName,nodeAddress,currentComp);
                                                           //Now if this tab this we just added is equal to the menu item of the split menu,
                                                           //store this so that we can give focus to it later
                                                           if (splitTabName.equals(nodeAddress))
                                                                iIndexOfSplit = _viewTabPane.getTabCount()-1;
                                            //Also remove it from our vector of merged tabs
                                            _qmMergedIndexes.remove(tabStr);
                                            //int mergeIndex = _viewTabPane.indexOfTab(splitTabName);
                                            //if (mergeIndex != -1)
                                                      if (iIndexOfSplit != -1)
                                                //_viewTabPane.setSelectedIndex(mergeIndex);
                                                           _viewTabPane.setSelectedIndex(iIndexOfSplit);
                                    splitMenu.add(mergeItem);
                            popup.add(menuItem1);
                            popup.add(merge);
                            popup.add(splitMenu);
                            if (popup != null)
                                Point p = e.getPoint();
                                popup.show((Component)e.getSource(), (int)p.getX(), (int)p.getY());
                    public void mouseEntered(MouseEvent e)
                    public void mouseExited(MouseEvent e)
                    public void mousePressed(MouseEvent e)
                    public void mouseReleased(MouseEvent e)
                   //Don't forget to add the tree's
                   addTreeDisplays();
                _viewTabPane.addTab(StringFactory.getString("perspective.display.overview.tab"), _treeTabPane);
                   _viewTabPane.addTab(StringFactory.getString("perspective.display.documentation.tab"), new DocDisplayPanel());
                _mainDisplayPanel.add(_viewTabPane, BorderLayout.CENTER);
            catch(Exception e)
                e.printStackTrace();
         private void addTabToDisplay(String nameStr, String toolStr, JComponent c)
              if (_viewTabPane == null)
                   return;
              _viewTabPane.addTab(nameStr, c);
              int tabNum = _viewTabPane.getTabCount()-1;
              if (toolStr != null)
                   _viewTabPane.setToolTipTextAt(tabNum, toolStr);
              _viewTabPane.setSelectedIndex(tabNum);
         private void addTreeDisplays()
              String starKey = StringFactory.getString(starviewKey);
              String treeKey = StringFactory.getString(treeviewKey);
              //navigatorTreePanel.expandTreePath(this, true);
              String test = MQEPreferencesDialog.getPreferenceValue("expand.leaf.startup");
              System.out.println("test{{{{{{{{{{"+test);
              //System.out.println("test{{{{{{{{{{"+m_nnode.);
              if (treeDisplayPreference == BOTH_DISPLAY)
                   hyperbolicTreePanel = new HyperbolicTreePanel(m_model);
                   hyperbolicTreePanel.addQMRequestListener(this);
                   hyperbolicTreePanel.addTopologySelectionListener(this);
                   //hyperbolicTreePanel.expandTreePath((TopologyModelNode)m_model.getRoot(), true);
                   //hyperbolicTreePanel.expandTreePath(m_nnode, true);
                   _treeTabPane.addTab("", IconFactory.getInstance().getIcon("staricon"), hyperbolicTreePanel, starKey);
                   navigatorTreePanel = new NavigatorTreePanel(m_model);
                   navigatorTreePanel.addQMRequestListener(this);
                   navigatorTreePanel.addTopologySelectionListener(this);
                   _treeTabPane.addTab("", IconFactory.getInstance().getIcon("treeicon"), navigatorTreePanel, treeKey);
              else if (treeDisplayPreference == TREE_DISPLAY)
                   navigatorTreePanel = new NavigatorTreePanel(m_model);
                   navigatorTreePanel.addQMRequestListener(this);
                   navigatorTreePanel.addTopologySelectionListener(this);
                   _treeTabPane.addTab("", IconFactory.getInstance().getIcon("treeicon"), navigatorTreePanel, treeKey);
              else
                   hyperbolicTreePanel = new HyperbolicTreePanel(m_model);
                   hyperbolicTreePanel.addQMRequestListener(this);
                   hyperbolicTreePanel.addTopologySelectionListener(this);
                   _treeTabPane.addTab("", IconFactory.getInstance().getIcon("staricon"), hyperbolicTreePanel, starKey);
        public void addTopologySelectionListener(TopologySelectionListener tsl)
            if (tsl != null)
                _tsListeners.add(tsl);
        public void removeTopologySelectionListener(TopologySelectionListener tsl)
            if (tsl != null)
                _tsListeners.remove(tsl);
        protected void fireTopologySelection(TopologyModelNode node)
            for (TopologySelectionListener tsl : _tsListeners)
                tsl.receiveTopologySelection(node);
       /* TopologySelectionListener methods                                     */
        public void receiveTopologySelection(TopologyModelNode node)
            //Since this panel can have multiple panels in it's current Tabbed display.
            //This class registers to each of the TopologyDisplayPanels as a listener for selections
            //This way no matter who is currently active, they will funnel the event to here and it this
            //panel will send the event on foward
            if (node != null)
                fireTopologySelection(node);
       /* QMRequestListener methods                                             */
        public void receiveQMRequest(TopologyModelNode node)
            //Check to see if this node is already in a Tab already
            System.out.println("Queue Manager request");
              boolean doesExist = false;
            int tabNum =0;
              //Fix for activity 00033248 TAB PANES FOR IDENTICAL QMANAGERS ON DIFF MACHINES
              //The only unique names are in the tooltips so lets just cycle through all the tabs
              //and search for this Queue Manager name.  Using indexOfTab in JTabbedPane will not
              //work here because it will return first location of a matching queue manager name, but
              //we could have multiple tabs open with same queue manager name.
              for (int i = 0; i < _viewTabPane.getTabCount();i++)
                   String toolTipStr = _viewTabPane.getToolTipTextAt(i);
                   //Using the string method for indexOf, covers us when we have a merged tab window
                   if ((toolTipStr != null) && (toolTipStr.indexOf(((ResourceProxy)node).getAddress().trim()) != -1))
                        //We already have existing queue manager tab open
                        doesExist = true;
                        tabNum = i;
                        break;
              if ( !doesExist)
                   //Create the tab
                NavigatorTreePanel treePanel = new NavigatorTreePanel(new ExpandingModelNode(node));
                treePanel.addTopologySelectionListener(this);
                   // Add the tree panel to a container so that it can be accessed
                   // for expand/collapse all and tree refresh actions.
                   qmgrTreeDisplays.add(treePanel);
                   //Fix for activity 00033248 TAB PANES FOR IDENTICAL QMANAGERS ON DIFF MACHINES
                   addTabToDisplay(((ResourceProxy)node).getName().trim(), ((ResourceProxy)node).getAddress().trim(), treePanel);
                node.getModel().expandNode(node);
              else
                   _viewTabPane.setSelectedIndex(tabNum);
       /* PropertyChangeListener methods                                        */
            public void propertyChange(PropertyChangeEvent evt){
              String propertyChanged = evt.getPropertyName();
              if (propertyChanged.equals(MQEDisplayPreferences.treeDisplayProperty)){
                   int newPreference = ((Integer)evt.getNewValue()).intValue();
                   changeTreeDisplays(newPreference);
              else if (propertyChanged.equals(MQEDisplayPreferences.expandLeafProperty)){
                   // The enable leaf node preference has changed so update the MQE
                   // tree displays according to the new preference setting.
                   refreshTreeDisplays();
              else{
                   // Ignore the property change event.
        * Changes the trees displayed by MQE according to
         * the preference set by the current user.
        * @param the new trees display preference.*/
         public void changeTreeDisplays(int preference)
              // Assign the new tree display preference.
              treeDisplayPreference = preference;
              // Recreate the tree display according
              // to the new preference.
              m_model.removeTreeModelListeners();
              _treeTabPane.removeAll();
              addTreeDisplays();
              refreshTreeDisplays();
        * Fully expands the Navigator display trees from the specified node.
        * @param the node from which each tree will be fully expanded.
         public void expandAll(TopologyModelNode node)
              node.expandAll();
              final TopologyModelNode fnode = node;
              Runnable doTask = new Runnable(){
                   public void run(){
                        // Fire a tree structure changed notification for
                        // the StarTree, (1) because it will not display
                        // tree nodes correctly without it and (2) it appears
                        // to be the only tree interested in doing anything
                        // with it!
                        fnode.fireTreeStructureChanged(TopologyModel.STRUCTURE_CHANGE);
                        if (hyperbolicTreePanel != null)
                             hyperbolicTreePanel.expand(fnode);
                        if (navigatorTreePanel != null)
                             navigatorTreePanel.expand(fnode);
                        for (NavigatorTreePanel navTreePanel : qmgrTreeDisplays){
                             navTreePanel.expand(fnode);
              SwingUtilities.invokeLater(doTask);
        * Fully collapses the Navigator display trees from the specified node.
        * @param the node from which each tree will be fully collapsed.
         public void collapseAll(TopologyModelNode node)
              final TopologyModelNode fnode = node;
              Runnable doTask = new Runnable(){
                   public void run(){
                        if (hyperbolicTreePanel != null)
                             hyperbolicTreePanel.collapse(fnode);
                        if (navigatorTreePanel != null)
                             navigatorTreePanel.collapse(fnode);
                        for (NavigatorTreePanel navTreePanel : qmgrTreeDisplays){
                             navTreePanel.collapse(fnode);
              SwingUtilities.invokeLater(doTask);
        * Will ensure that all tree nodes, starting from the root, are correctly displayed.
         public void refreshTreeDisplays()
              if (hyperbolicTreePanel != null){
                   TopologyModel model = hyperbolicTreePanel.getTopologyModel();
                   if (model != null){
                        hyperbolicTreePanel.expandTreePath((TopologyModelNode)model.getRoot(), true);
                        hyperbolicTreePanel.refreshTreeDisplay((TopologyModelNode)model.getRoot());
              if (navigatorTreePanel != null){
                   TopologyModel model = navigatorTreePanel.getTopologyModel();
                   if (model != null){
                        navigatorTreePanel.refreshTreeDisplay((TopologyModelNode)model.getRoot());
                        navigatorTreePanel.repaint();
              for (NavigatorTreePanel navTreePanel : qmgrTreeDisplays){
                   ExpandingModelNode model = (ExpandingModelNode)navTreePanel.getNavigatorTreeModel();
                   if (model != null){
                        navigatorTreePanel.expand((TopologyModelNode)model.getRoot());
                        navTreePanel.refreshTreeDisplay((TopologyModelNode)model.getRoot());
                        navTreePanel.repaint();
    }

    you really don't need to post all that code, few people will read it, or try to compile/run it.
    just a tree in a scrollpane in a frame is all you need, then add the method/problem to the basic,
    and post that so its only 20 to 30 lines long.
    here's your basic tree/scrollpane/frame, with an expandAll()
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        JTree tree = new JTree();
        expandAll(tree);
        JFrame f = new JFrame();
        f.getContentPane().add(new JScrollPane(tree));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public void expandAll(JTree tree)
        int row = 0;
        while (row < tree.getRowCount())
          tree.expandRow(row);
          row++;
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }so, is your problem with the expandAll(), or with reading the properties file?

  • Exception in thread "main" java.lang.OutOfMemoryError(please help me )

    Hi All
    here my java class trying to read a txt file(which is having size of 60MB).and putting each line into a Vector class. problem is ,upto certain number of line it is reading properly and putting into vector..after that it is giving error like Exception in thread "main" java.lang.OutOfMemoryError..what is the problem and how to rectify this one..anybody help me on this.
    actual situation is one txt is there in that 80 lakhs of lines of content is there..java file trying to read each line and put it into vector or stringbuffer and split it into two lines like key=value and put it into hashmap object.then finally iam creating new file(.properties) and writing these hashmap data on it. if you want clearly..please look into below code..
    package test.utf8; import java.io.*; import java.util.*; public class AssetUtils
    //static StringBuffer stringbuffer = new StringBuffer();
    public AssetUtils()
    public static void main(String args[]) throws IOException
    BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\list.txt")));
    Vector vector = new Vector(0x30D40, 50000);
    System.out.println(vector.capacity());
    Object obj = null;
    int n=0;
    System.out.println("Reading list:" + new Date(System.currentTimeMillis()));
    do
    String s = bufferedreader.readLine();
    //System.out.println("line no: "+ ++n);
    if(s == null)
    break;
    vector.add(s);
    } while(true);
    System.out.println("List Read complete:" + new Date(System.currentTimeMillis()));
    String s1 = args[0];
    System.out.println("S1: "+s1);
    System.out.println(vector.capacity());
    HashMap hashmap = new HashMap();
    System.out.println( "Vector.Size..>>>>>>>>>>>>>>>>.."+vector.size());
    for(int i = 0; i < vector.size(); i++)
    System.out.println("i value:"+i);
    String s2 = (String)vector.get(i);
    //System.out.println("S2: "+s2);
    if(s2.indexOf("/") != -1)
    String s3 = s2.substring(s1.length(), s2.length());
    //System.out.println("S3: "+s3);
    if(s3.indexOf("/") != -1) {
    String s4 = s3.substring(0, s3.lastIndexOf("/"));
    //System.out.println("S4: "+s4);
    String s6 = s3.substring(s3.lastIndexOf("/") + 1, s3.length());
    //System.out.println("S6: "+s6);
    StringBuffer stringbuffer=null;
    stringbuffer = new StringBuffer();
    String s8 = (String)hashmap.get(s4);
    //System.out.println("S8: "+s8);
    if(s8 != null) stringbuffer.append(s8 + "," + s6);
    else
    stringbuffer.append(s6);
    hashmap.put(s4, stringbuffer.toString());
    //stringbuffer.delete(0,stringbuffer.length());
    stringbuffer=null;
    System.out.println("Opening asset.properties:" + new Date(System.currentTimeMillis()));
    File file = new File("D:\\asset.properties");
    PrintWriter printwriter = new PrintWriter(new FileOutputStream(file));
    String s5;
    String s7;
    for(Iterator iterator = hashmap.keySet().iterator(); iterator.hasNext(); printwriter.println(s5 + "=" + s7))
    { s5 = (String)iterator.next(); s7 = (String)hashmap.get(s5); } printwriter.close();
    System.out.println("Closing asset.properties:" + new Date(System.currentTimeMillis()));

    Theres a number of ways you can improve your memory usage:
    1) Build you map as you read in your file.
    2) Use StringBuffers in your map - do not use "asshaj" + "ashaskj" This is very memory intensive
    If you still run out of memory try running the JVM using -Xms128m -Xmx512m or higher

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

  • Persistent Bean framework

    I am struggling with an architectural question, surrounding persistent beans. Here is the problem.
    Supposed I have two classes, Group and Person. Obviously, Group contains some number of members. Thus, Group has a private HashMap (could have been Vector, but HashMap guarantees unique entries) listing all Person members. Finally, Group has get/set methods for its list of members.
    I have a simple persistence framework, whereby a "manager" can Introspect a bean, find all its properties, then save them to a data store, commonly a JDBC store, but in this case LDAP (using JNDI).
    The problem becomes how best to represent the Person members in the Group class. I could represent them as a Vector/HashMap/array of Person, but then persisting the Group becomes difficult, since when the manager Introspects the Group and finds the list of Person objects, it does not have basic elements to persist but rather complex user-defined Person objects. I do not want to store serialized objects, which make the data specific to my application, but rather the properties, so that the data can be used by other apps.
    When my data store was an RDBMS, I simply stored IDs for the list of members, since this mapped nicely to a relational model. However, in the case of an LDAP store, the member attributes (representing the list) contain a DN rather than just the ID (which is inside the DN).
    Here is my catch-22: if I store the serialized Person objects or even just the unique IDs of the Persons, then the underlying data in the LDAP directory become unique to my app; if I somehow get it to translate to the entire DN representing the Person, then my application objects become specific to my LDAP store and not reusable in other storage contexts.
    Any ideas?

    Hi Jhon,
    Nothing like that exists for DB XML at the moment. Berkeley DB JE supports object persistence in Java using simple annotations, if that's what you need.
    John

  • Vector with in a 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?

    Crosspost http://forum.java.sun.com/thread.jspa?threadID=758181&messageID=4330541#4330541

  • Vector does not retain values in hashmap

    There should be 200 different values in Vector Group_Privs, but all the values is the last value retrieved. Help!
    Map map = new HashMap();
    Vector Group_Privs = new Vector();
    Database database = new Database();
    ResultSet result = null;
    String connection = Connection;
    try
    Connection con = database.getDesiredConnection(Connection);
    PreparedStatement ps = null;
    try
    ps = con.prepareStatement("select GROUP_ID"
    +" from group_table ");
    result = ps.executeQuery();
    int i=0;
    while (result.next())
    map.put ("GROUP_ID",(String)result.getString(1));
    Group_Privs.add(map);
    result.close();

    import java.util.*;
    public class Example {
        public static void main(String[] args) {
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            addValues(list);
            retrieveValues(list);
        static void addValues(List<Map<String, String>> list) {
            for(int i=0; i<4; ++i) {
                Map<String, String> map = new HashMap<String, String>();
                for(int j=0; j<=i; ++j) {
                    String s = String.valueOf(j);
                    map.put(s, s);
                list.add(map);
        static void retrieveValues(List<Map<String, String>> list) {
            for(Map<String, String> map : list) {
                System.out.format("%nmap of size %d: %n", map.size());
                for(Map.Entry<String, String> e : map.entrySet()) {
                    System.out.format("%s |-> %s%n", e.getKey(), e.getValue());
    }[http://java.sun.com/docs/books/tutorial/collections/index.html]

  • Vector as a HashMap key

    Hi all, I want to use Vector position as a key of hash map. Do you think that it is work? And could you mind show me some sample code. Thanks!!!

    It'll work. Here's some code that follows. However, in my sample, I'd rather store 'user' as the key to the HashMap. Also, the code below won't allow for the list to be sorted or anything after it is added to the HashMap.
    import java.util.*;
    public class VectorAndHashMap
        static class Preference
            String color;
            String fontSize;
            public Preference(String _color, String _fontSize) {
                color=_color;
                fontSize=_fontSize;
            public String toString() {
                return color+"/"+fontSize;
        public static void main(String[] args)
            Object[] users = {"smith", "brown", "jones"};
            // create the Vector
            Vector v = new Vector(Arrays.asList(users));
            Object[] prefs = { new Preference("blue", "big"),     // smith's
                               new Preference("blue", "small"),   // brown's
                               new Preference("red", "medium") }; // jones's
            // create the HashMap
            HashMap hashmap = new HashMap();
            // load the HashMap
            for(int i=0; i<v.size(); i++)
                hashmap.put(new Integer(i), prefs);
    // lookup index for "brown"
    int j=0;
    boolean found = false;
    for(j=0; j<v.size(); j++) {
    String user = (String)v.get(j);
    if(user.equals("brown")) {
    found = true;
    break;
    // retrieve record
    if(found) {
    Preference pref = (Preference)hashmap.get(new Integer(j));
    System.out.println("brown's record: " + pref);

  • Problem in setting vector or string[] as the "value object" in hashmap

    Hey I am new to this forum.
    I am doing a project in which i need to store a array of strings as "value object" for a unique key in hashmap.
    as I populate the hashmap from external file according to key and setting the string[]. The hashmap is taking the value field same for each entry i.e the last field as i keep updating the same variable and then putting it into hashmap.
    Please give solution to my problem???
    if question not clear,please tell me- i will add more information
    Edited by: AnkitNahar on Apr 4, 2009 8:06 AM

    I tried using the method suggested by you...but it is of same case as using the string[].
    I need to loop the statements in which the hashmap is populating so cant change the variable names in the dd.put() statements. When the below code executes it shows the same set of string for both the keys, that was the problem i was facing with string[].
    here is the example with two entries....same thing in looping.
    HashMap<String,Set<String>> dd=new HashMap<String,Set<String>>();
    String word = "Hello";
    Set<String> alternativeWords = new HashSet<String>();
    alternativeWords.add("Hi");
    alternativeWords.add("Yo");
    dd.put(word, alternativeWords);
    alternativeWords.clear();
    alternativeWords.add("hey");
    word="yep";
    dd.put(word,alternativeWords);
    System.out.println(dd.get("Hello").toString());
    System.out.println(dd.get("yep").toString());

Maybe you are looking for