Casting Enumeration to Iterator

The element() method of a Hashtable returns an Enumeration Object.
I got the following code working fine...
Hashtable h = new HashTable);
// Things with the hashtable
Iterator i =(Iterator) h.elements();
//Here I am CASTING Elnumeration to Iterator
while (i.hasNext()) {
// i.next() kind of things
Is this correct ???

Many iterators implement both java.util.Enumeration and java.util.Iterator, but you shouldn't count on it.
- Marcus

Similar Messages

  • Enumeration vs Iterator

    Please,
    what is the difference between iterator and enumeration? Iterator should be more better designed, but I don't note that difference.

    Iterator vs. Enumeration
    Round 1: Typing
    "Iterator" has fewer letters than "Enumeration" (Point to Iterator)
    Iterator's methods have fewer letters than Enumeration's methods (Point to Iterator)
    Round 2: Power
    Iterator advertises the ability to remove from the iterated collection the last element that has been returned. Enumeration has no facility to do that. (Point to Iterator)
    Iterator has been extended within the Java platform (see ListIterator) to advertise the ability to move forward or backward through the iterated collection. (Point to Iterator)
    This extension can also add an element to the collection and change the value of the last element returned within the collection. (Point to Iterator)
    Iterator is integrated into the Collections framework. Enumeration is peripheral to the framework and has been awkwardly inserted to provide backwards compatability to Dinosaur-aged programs. (Point to Iterator)
    Lexographically speaking, Enumeration comes before Iterator. (Point to Enumeration).
    Tally up the score. You be the judge :-)

  • Enumeration and Iterator

    what is the different between Enumeration and Iterator ?

    http://forum.java.sun.com/thread.jspa?threadID=596382&tstart=255

  • Enumeration/iteration definitions

    Could someone explain to me the difference between enumeration and iteration? Do either of them do anything special to the contents of a vector?
    I have a vector that contains something like [6, +, 9, *, 15, +, 10]. What I need to do is turn this into an equation and calculate it. i.e. x=6+9*15+10;
    Can this be accomplished by the use of an interator or enumerator? Or am I way off base? Another solution I thought of is to use toString() for the Vector, and then convert the numeric Strings into integers, but have no idea what to do with the operators as I do not believe Java considers them Strings.

    Thanks for letting me know the difference, it wasn't really clear in the book I have.
    The solution you suggested is what I feared. I was hoping Java had some way to recognize the String version of +-*/ as operators. It seems strange to me to have to write a parser to tell it what to do when it sees +-*/ and to tell it the order to evaluate them in. Silly to have to redefine what is already built into Java.
    Probably looks like I shouldn't waste my time putting these items into a Vector, they start out in a String format with some additional characters and I have used a StringTokenizer to eliminate the extra chars and put the tokens and delimiters into a Vector. Guess that is overkill, although I thought it would make it easier. Looks like I should call some sort of parsing method while tokenizing or something.

  • Iterator issue

    using
    <%@ page import="java.io.*,java.util.*" %>
    <!-- <%@ page import="java.util.Iterator" %> -->
    <html>
    <head>
    <title>Thank You</title>
    </head>
    <body>
    Your form contains the following elements.
    <ul>
    <%
    for (Iterator f = (Iterator) request.getParameterNames(); f.hasNext(); )
    out.print("<li>");
    out.print(f.next());
    out.print("</li>");
    %>
    </ul>
    </body>
    </html>
    the servlet fails with a type cast problem:
    however:
    <%@ page import="java.util.*" %>
    <html>
    <head>
    <title>Thank You</title>
    </head>
    <body>
    Your form contains the following elements.
    <ul>
    <%
    for (Enumeration f = (Enumeration) request.getParameterNames(); f.hasMoreElements(); )
    out.print("<li>");
    out.print(f.nextElement());
    out.print("</li>");
    %>
    </ul>
    </body>
    </html>
    does not .
    I thought Enumeration and Iterator were about the same and Enumeration was going away so Iterator was the way to go. But the typecast fails. Why is this? And how could I make a java servlet to test situations like this?
    Thanks

    Just look in the API documentation and see whether the method you are using returns an Enumeration or an Iterator. They aren't the same thing, and saying that one "is going away" doesn't mean that the designers will go back to existing code and replace Enumerations by Iterators; that would break thousands of people's code.

  • Can you remove elements of hash while enumerating through its keys?

    I am running through each element of a hash table using the keys() method which returns an
    enumeration. Some values I will wish to remove from the hash after I view them while I am still enumerating through its keys. Can you do this without causing an error in the next call enumeration.nextElement()? I know its not a good idea to do this when using an iterator, but I didn't see any documentaion about it regarding enumerations. I could do a test run to check this but I'm not sure that that proves anything, I don't want it to fail ever.

    It's never a good idea to remove or add elements to a collection except by means of the enumerator or iterator that you've got for it. I don't know of any collections library in any language that allows this operation.
    You may be referring to the fact that Iterators are fail-fast, meaning that you get an error if you change the collection while you've got an iterator on it. But this is a good thing, because it alerts you to the fact that you're doing something horribly wrong. With an Enumerator, the code will simply silently fail. :-(

  • # of elements in an enumeration?

    Hi there!
    Does any of you know a way to count the number of elements in an enumeration without iterating through them?
    Thanks in advance!

    Can't be done. You could create a class that implements Enumeration and does the counting but you still end up iterating through the enumeration. It's just abstracted.

  • Vector enumeration?

    while using vectors why enumeration is done?

    Are you asking why Sun provided the Enumeration class?
    If so, I always tend to think in terms of substitutability. The Enumeration and Iterator interfaces provide a standardised way to iterate over the members of a collection. Thus the impact on other code of changing the type of the collection used may be minimised.
    PS Agree with the previous poster. Unless you need to thread safe features of the Vector, why use it?

  • What to do when readString() fails and String[] out of bounds ?

    Dear Java People,
    I have a runtime error message that says:
    stan_ch13_page523.InvalidUserInputException: readString() failed. Input data is not a string
    java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    below is the program
    thank you in advance
    Norman
    import java.io.*;
    import java.util.*;
    public class FormattedInput
        // Method to read an int value
        public int readInt()
          for(int i = 0; i < 2; i ++)
          if(readToken() == tokenizer.TT_NUMBER)
            return (int)tokenizer.nval;   // value is numeric so return as int
          else
            System.out.println("Incorrect input: " + tokenizer.sval +
               " Re-enter as integer");
            continue;         //retry the read operation
          } // end of for loop
          System.out.println("Five failures reading an int value" + " - program terminated");
          System.exit(1);  // end the program
          return 0;
         public double readDouble() throws InvalidUserInputException
           if(readToken() != tokenizer.TT_NUMBER)
              throw new InvalidUserInputException(" readDouble() failed. " + " Input data not numeric");
           return tokenizer.nval;
         public String readString() throws InvalidUserInputException
           if(readToken() == tokenizer.TT_WORD || ttype == '\"' ||  ttype == '\'')
            return tokenizer.sval;
           else
             throw new InvalidUserInputException(" readString() failed. " + " Input data is not a string");
           //helper method to read the next token
           private int readToken()
             try
               ttype = tokenizer.nextToken();
               return ttype;
             catch(IOException e)
               e.printStackTrace(System.err);
               System.exit(1);
              return 0;
           //object to tokenize input from the standard input stream
           private StreamTokenizer tokenizer = new StreamTokenizer(
                                                new BufferedReader(
                                                 new InputStreamReader(System.in)));
           private int ttype;                  //stores the token type code
    import java.io.*;
    import java.util.*;
    public class TryVectorAndSort
         public static void main(String[] args)
        Person aPerson;           // a Person object
        Crowd filmCast = new Crowd();
        //populate the crowd
        for( ; ;)
          aPerson = readPerson();
          if(aPerson == null)
            break;   // if null is obtained we break out of the for loop
          filmCast.add(aPerson);
        int count = filmCast.size();
        System.out.println("You added " + count + (count == 1 ? " person":  " people ") + "to the cast.\n");
        //Show who is in the cast using an iterator
         Iterator myIter = filmCast.iterator();
        //output all elements
        while(myIter.hasNext() )
          System.out.println(myIter.next());
        }//end of main
          //read a person from the keyboard
          static public Person readPerson()
         FormattedInput in = new FormattedInput();
            //read in the first name and remove blanks front and back
            System.out.println("\nEnter first name or ! to end:");
            String firstName = "";
            try
            firstName = in.readString().trim(); //read and trim a string
            catch(InvalidUserInputException e)
            e.printStackTrace(System.err);
            //check for a ! entered. If so we are done
            if(firstName.charAt(0) == '!')
              return null;
            //read the last name also trimming the blanks
            System.out.println("Enter last name:");
            String lastName= "";
            try
              lastName = in.readString().trim(); //read and trim a string
            catch(InvalidUserInputException e)
             e.printStackTrace(System.err);
            return new Person(firstName, lastName);
    //when I ran the program the output I received was:
    import java.io.StreamTokenizer;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    public class InvalidUserInputException extends Exception
       public InvalidUserInputException() { }
          public InvalidUserInputException(String message)
              super(message);
    import java.util.*;
    class Crowd
      public Crowd()
        //Create default Vector object to hold people
         people = new Vector();
      public Crowd(int numPersons)
        //create Vector object to hold  people with given capacity
         people = new Vector(numPersons);
        //add a person to the crowd
        public boolean add(Person someone)
          return people.add(someone);
         //get the person at the given index
          Person get(int index)
          return (Person)people.get(index);
         //get the numbers of persons in the crowd
          public int size()
            return people.size();
          //get  people store capacity
          public int capacity()
            return people.capacity();
          //get a listIterator for the crowd
          public Iterator iterator()
            return people.iterator();
            //A Vector implements the List interface (that has the static sort() method
            public void sort()
              Collections.sort(people);
          //Person store - only accessible through methods of this class
          private Vector people;
    public class Person implements Comparable
      public Person(String firstName, String lastName)
        this.firstName = firstName;
        this.lastName = lastName;
      public String toString()
        return firstName + "  " + lastName;
       //Compare Person objects
        public int compareTo(Object person)
           int result = lastName.compareTo(((Person)person).lastName);
           return result == 0 ? firstName.compareTo(((Person)person).firstName):result;
      private String firstName;
      private String lastName;

    Dear Nasch,
    ttype is declared in the last line of the FormattedInput class
    see below
    Norman
    import java.io.*;
    import java.util.*;
    public class FormattedInput
        // Method to read an int value
        public int readInt()
          for(int i = 0; i < 2; i ++)
          if(readToken() == tokenizer.TT_NUMBER)
            return (int)tokenizer.nval;   // value is numeric so return as int
          else
            System.out.println("Incorrect input: " + tokenizer.sval +
               " Re-enter as integer");
            continue;         //retry the read operation
          } // end of for loop
          System.out.println("Five failures reading an int value" + " - program terminated");
          System.exit(1);  // end the program
          return 0;
         public double readDouble() throws InvalidUserInputException
           if(readToken() != tokenizer.TT_NUMBER)
              throw new InvalidUserInputException(" readDouble() failed. " + " Input data not numeric");
           return tokenizer.nval;
         public String readString() throws InvalidUserInputException
           if(readToken() == tokenizer.TT_WORD || ttype == '\"' ||  ttype == '\'')
             System.out.println(tokenizer.sval);
            return tokenizer.sval;
           else
             throw new InvalidUserInputException(" readString() failed. " + " Input data is not a string");
           //helper method to read the next token
           private int readToken()
             try
               ttype = tokenizer.nextToken();
               return ttype;
             catch(IOException e)
               e.printStackTrace(System.err);
               System.exit(1);
              return 0;
           //object to tokenize input from the standard input stream
           private StreamTokenizer tokenizer = new StreamTokenizer(
                                                new BufferedReader(
                                                 new InputStreamReader(System.in)));
           private int ttype;                  //stores the token type code
         }

  • How to make treetable transparent

    hi,
    Does anyone have idea how to make the treetable transparent so that the background image can be shown?
    Pls provide sample code if possible,thanks!

    I don't know if I can come up with some code example
    for you since I don't know what treetable your are
    using... but... Transparency is always going to relate
    to the whether your components are opaque or not.
    Opaque = Not Transparent, so setting opaque = false
    will hopefully make your table transparent. You may
    need to do this on your CellRenderer's as well.
    Hope this helps,
    Josh Castagno
    http://www.jdc-software.com
    hi,
    i am using JTreeTable provided fron Sun swing connection article,by Scott Violet and Kathy Walrath.
    The situation i am facng now is jtree able to be transparent, but jtable still using it default background.
    Below are excerpt from sample, setOpaque(false) to jtable seem doesn't take effect.
    As i an newbie to swing,kindly point out where part shd i modified on the code. Thz!
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import java.util.EventObject;
    * This example shows how to create a simple JTreeTable component,
    * by using a JTree as a renderer (and editor) for the cells in a
    * particular column in the JTable.
    * @version 1.2 10/27/98
    * @author Philip Milne
    * @author Scott Violet
    public class JTreeTable extends JTable {
    /** A subclass of JTree. */
    protected TreeTableCellRenderer tree;
    public JTreeTable(TreeTableModel treeTableModel) {
         super();
         // Creates the tree. It will be used as a renderer and editor.
         tree = new TreeTableCellRenderer(treeTableModel);
         // Installs a tableModel representing the visible rows in the tree.
         super.setModel(new TreeTableModelAdapter(treeTableModel, tree));
         // Forces the JTable and JTree to share their row selection models.
         ListToTreeSelectionModelWrapper selectionWrapper = new
         ListToTreeSelectionModelWrapper();
         tree.setSelectionModel(selectionWrapper);
         setSelectionModel(selectionWrapper.getListSelectionModel());
         // Installs the tree editor renderer and editor.
         setDefaultRenderer(TreeTableModel.class, tree);
         setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
         // No grid.
         setShowGrid(false);
    //added
    setOpaque(false);
         // No intercell spacing
         setIntercellSpacing(new Dimension(0, 0));     
         // And update the height of the trees row to match that of
         // the table.
         if (tree.getRowHeight() < 1) {
         // Metal looks better like this.
         setRowHeight(20);
    * Overridden to message super and forward the method to the tree.
    * Since the tree is not actually in the component hierarchy it will
    * never receive this unless we forward it in this manner.
    public void updateUI() {
         super.updateUI();
         if(tree != null) {
         tree.updateUI();
         // Do this so that the editor is referencing the current renderer
         // from the tree. The renderer can potentially change each time
         // laf changes.
         setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
         // Use the tree's default foreground and background colors in the
         // table.
    LookAndFeel.installColorsAndFont(this, "Tree.background",
    "Tree.foreground", "Tree.font");
    * Workaround for BasicTableUI anomaly. Make sure the UI never tries to
    * resize the editor. The UI currently uses different techniques to
    * paint the renderers and editors; overriding setBounds() below
    * is not the right thing to do for an editor. Returning -1 for the
    * editing row in this case, ensures the editor is never painted.
    public int getEditingRow() {
    return (getColumnClass(editingColumn) == TreeTableModel.class) ? -1 :
         editingRow;
    * Returns the actual row that is editing as <code>getEditingRow</code>
    * will always return -1.
    private int realEditingRow() {
         return editingRow;
    * This is overridden to invoke super's implementation, and then,
    * if the receiver is editing a Tree column, the editor's bounds is
    * reset. The reason we have to do this is because JTable doesn't
    * think the table is being edited, as <code>getEditingRow</code> returns
    * -1, and therefore doesn't automatically resize the editor for us.
    public void sizeColumnsToFit(int resizingColumn) {
         super.sizeColumnsToFit(resizingColumn);
         if (getEditingColumn() != -1 && getColumnClass(editingColumn) ==
         TreeTableModel.class) {
         Rectangle cellRect = getCellRect(realEditingRow(),
                             getEditingColumn(), false);
    Component component = getEditorComponent();
         component.setBounds(cellRect);
    component.validate();
    * Overridden to pass the new rowHeight to the tree.
    public void setRowHeight(int rowHeight) {
    super.setRowHeight(rowHeight);
         if (tree != null && tree.getRowHeight() != rowHeight) {
    tree.setRowHeight(getRowHeight());
    * Returns the tree that is being shared between the model.
    public JTree getTree() {
         return tree;
    * Overridden to invoke repaint for the particular location if
    * the column contains the tree. This is done as the tree editor does
    * not fill the bounds of the cell, we need the renderer to paint
    * the tree in the background, and then draw the editor over it.
    public boolean editCellAt(int row, int column, EventObject e){
         boolean retValue = super.editCellAt(row, column, e);
         if (retValue && getColumnClass(column) == TreeTableModel.class) {
         repaint(getCellRect(row, column, false));
         return retValue;
    * A TreeCellRenderer that displays a JTree.
    public class TreeTableCellRenderer extends JTree implements
         TableCellRenderer {
         /** Last table/tree row asked to renderer. */
         protected int visibleRow;
         /** Border to draw around the tree, if this is non-null, it will
         * be painted. */
         protected Border highlightBorder;
         public TreeTableCellRenderer(TreeModel model) {
         super(model);
         * updateUI is overridden to set the colors of the Tree's renderer
         * to match that of the table.
         public void updateUI() {
         super.updateUI();
         // Make the tree's cell renderer use the table's cell selection
         // colors.
         TreeCellRenderer tcr = getCellRenderer();
         if (tcr instanceof DefaultTreeCellRenderer) {
              DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer)tcr);
              // For 1.1 uncomment this, 1.2 has a bug that will cause an
              // exception to be thrown if the border selection color is
              // null.
              // dtcr.setBorderSelectionColor(null);
              dtcr.setTextSelectionColor(UIManager.getColor
                             ("Table.selectionForeground"));
              dtcr.setBackgroundSelectionColor(UIManager.getColor
                                  ("Table.selectionBackground"));
         * Sets the row height of the tree, and forwards the row height to
         * the table.
         public void setRowHeight(int rowHeight) {
         if (rowHeight > 0) {
              super.setRowHeight(rowHeight);
              if (JTreeTable.this != null &&
              JTreeTable.this.getRowHeight() != rowHeight) {
              JTreeTable.this.setRowHeight(getRowHeight());
         * This is overridden to set the height to match that of the JTable.
         public void setBounds(int x, int y, int w, int h) {
         super.setBounds(x, 0, w, JTreeTable.this.getHeight());
         * Sublcassed to translate the graphics such that the last visible
         * row will be drawn at 0,0.
         public void paint(Graphics g) {
         g.translate(0, -visibleRow * getRowHeight());
         super.paint(g);
         // Draw the Table border if we have focus.
         if (highlightBorder != null) {
              highlightBorder.paintBorder(this, g, 0, visibleRow *
                             getRowHeight(), getWidth(),
                             getRowHeight());
         * TreeCellRenderer method. Overridden to update the visible row.
         public Component getTableCellRendererComponent(JTable table,
                                  Object value,
                                  boolean isSelected,
                                  boolean hasFocus,
                                  int row, int column) {
         Color background;
         Color foreground;
         if(isSelected) {
              background = table.getSelectionBackground();
              foreground = table.getSelectionForeground();
         else {
              background = table.getBackground();
              foreground = table.getForeground();
         highlightBorder = null;
         if (realEditingRow() == row && getEditingColumn() == column) {
              background = UIManager.getColor("Table.focusCellBackground");
              foreground = UIManager.getColor("Table.focusCellForeground");
         else if (hasFocus) {
              highlightBorder = UIManager.getBorder
              ("Table.focusCellHighlightBorder");
              if (isCellEditable(row, column)) {
              background = UIManager.getColor
                   ("Table.focusCellBackground");
              foreground = UIManager.getColor
                   ("Table.focusCellForeground");
         visibleRow = row;
         setBackground(background);
         TreeCellRenderer tcr = getCellRenderer();
         if (tcr instanceof DefaultTreeCellRenderer) {
              DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer)tcr);
              if (isSelected) {
              dtcr.setTextSelectionColor(foreground);
              dtcr.setBackgroundSelectionColor(background);
              else {
              dtcr.setTextNonSelectionColor(foreground);
              dtcr.setBackgroundNonSelectionColor(background);
         return this;
    * An editor that can be used to edit the tree column. This extends
    * DefaultCellEditor and uses a JTextField (actually, TreeTableTextField)
    * to perform the actual editing.
    * <p>To support editing of the tree column we can not make the tree
    * editable. The reason this doesn't work is that you can not use
    * the same component for editing and renderering. The table may have
    * the need to paint cells, while a cell is being edited. If the same
    * component were used for the rendering and editing the component would
    * be moved around, and the contents would change. When editing, this
    * is undesirable, the contents of the text field must stay the same,
    * including the caret blinking, and selections persisting. For this
    * reason the editing is done via a TableCellEditor.
    * <p>Another interesting thing to be aware of is how tree positions
    * its render and editor. The render/editor is responsible for drawing the
    * icon indicating the type of node (leaf, branch...). The tree is
    * responsible for drawing any other indicators, perhaps an additional
    * +/- sign, or lines connecting the various nodes. So, the renderer
    * is positioned based on depth. On the other hand, table always makes
    * its editor fill the contents of the cell. To get the allusion
    * that the table cell editor is part of the tree, we don't want the
    * table cell editor to fill the cell bounds. We want it to be placed
    * in the same manner as tree places it editor, and have table message
    * the tree to paint any decorations the tree wants. Then, we would
    * only have to worry about the editing part. The approach taken
    * here is to determine where tree would place the editor, and to override
    * the <code>reshape</code> method in the JTextField component to
    * nudge the textfield to the location tree would place it. Since
    * JTreeTable will paint the tree behind the editor everything should
    * just work. So, that is what we are doing here. Determining of
    * the icon position will only work if the TreeCellRenderer is
    * an instance of DefaultTreeCellRenderer. If you need custom
    * TreeCellRenderers, that don't descend from DefaultTreeCellRenderer,
    * and you want to support editing in JTreeTable, you will have
    * to do something similiar.
    public class TreeTableCellEditor extends DefaultCellEditor {
         public TreeTableCellEditor() {
         super(new TreeTableTextField());
         * Overridden to determine an offset that tree would place the
         * editor at. The offset is determined from the
         * <code>getRowBounds</code> JTree method, and additionally
         * from the icon DefaultTreeCellRenderer will use.
         * <p>The offset is then set on the TreeTableTextField component
         * created in the constructor, and returned.
         public Component getTableCellEditorComponent(JTable table,
                                  Object value,
                                  boolean isSelected,
                                  int r, int c) {
         Component component = super.getTableCellEditorComponent
              (table, value, isSelected, r, c);
         JTree t = getTree();
         boolean rv = t.isRootVisible();
         int offsetRow = rv ? r : r - 1;
         Rectangle bounds = t.getRowBounds(offsetRow);
         int offset = bounds.x;
         TreeCellRenderer tcr = t.getCellRenderer();
         if (tcr instanceof DefaultTreeCellRenderer) {
              Object node = t.getPathForRow(offsetRow).
              getLastPathComponent();
              Icon icon;
              if (t.getModel().isLeaf(node))
              icon = ((DefaultTreeCellRenderer)tcr).getLeafIcon();
              else if (tree.isExpanded(offsetRow))
              icon = ((DefaultTreeCellRenderer)tcr).getOpenIcon();
              else
              icon = ((DefaultTreeCellRenderer)tcr).getClosedIcon();
              if (icon != null) {
              offset += ((DefaultTreeCellRenderer)tcr).getIconTextGap() +
                   icon.getIconWidth();
         ((TreeTableTextField)getComponent()).offset = offset;
         return component;
         * This is overridden to forward the event to the tree. This will
         * return true if the click count >= 3, or the event is null.
         public boolean isCellEditable(EventObject e) {
         if (e instanceof MouseEvent) {
              MouseEvent me = (MouseEvent)e;
              // If the modifiers are not 0 (or the left mouse button),
    // tree may try and toggle the selection, and table
    // will then try and toggle, resulting in the
    // selection remaining the same. To avoid this, we
    // only dispatch when the modifiers are 0 (or the left mouse
    // button).
              if (me.getModifiers() == 0 ||
    me.getModifiers() == InputEvent.BUTTON1_MASK) {
              for (int counter = getColumnCount() - 1; counter >= 0;
                   counter--) {
                   if (getColumnClass(counter) == TreeTableModel.class) {
                   MouseEvent newME = new MouseEvent
                   (JTreeTable.this.tree, me.getID(),
                        me.getWhen(), me.getModifiers(),
                        me.getX() - getCellRect(0, counter, true).x,
                        me.getY(), me.getClickCount(),
    me.isPopupTrigger());
                   JTreeTable.this.tree.dispatchEvent(newME);
                   break;
              if (me.getClickCount() >= 3) {
              return true;
              return false;
         if (e == null) {
              return true;
         return false;
    * Component used by TreeTableCellEditor. The only thing this does
    * is to override the <code>reshape</code> method, and to ALWAYS
    * make the x location be <code>offset</code>.
    static class TreeTableTextField extends JTextField {
         public int offset;
         public void reshape(int x, int y, int w, int h) {
         int newX = Math.max(x, offset);
         super.reshape(newX, y, w - (newX - x), h);
    * ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel
    * to listen for changes in the ListSelectionModel it maintains. Once
    * a change in the ListSelectionModel happens, the paths are updated
    * in the DefaultTreeSelectionModel.
    class ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel {
         /** Set to true when we are updating the ListSelectionModel. */
         protected boolean updatingListSelectionModel;
         public ListToTreeSelectionModelWrapper() {
         super();
         getListSelectionModel().addListSelectionListener
         (createListSelectionListener());
         * Returns the list selection model. ListToTreeSelectionModelWrapper
         * listens for changes to this model and updates the selected paths
         * accordingly.
         ListSelectionModel getListSelectionModel() {
         return listSelectionModel;
         * This is overridden to set <code>updatingListSelectionModel</code>
         * and message super. This is the only place DefaultTreeSelectionModel
         * alters the ListSelectionModel.
         public void resetRowSelection() {
         if(!updatingListSelectionModel) {
              updatingListSelectionModel = true;
              try {
              super.resetRowSelection();
              finally {
              updatingListSelectionModel = false;
         // Notice how we don't message super if
         // updatingListSelectionModel is true. If
         // updatingListSelectionModel is true, it implies the
         // ListSelectionModel has already been updated and the
         // paths are the only thing that needs to be updated.
         * Creates and returns an instance of ListSelectionHandler.
         protected ListSelectionListener createListSelectionListener() {
         return new ListSelectionHandler();
         * If <code>updatingListSelectionModel</code> is false, this will
         * reset the selected paths from the selected rows in the list
         * selection model.
         protected void updateSelectedPathsFromSelectedRows() {
         if(!updatingListSelectionModel) {
              updatingListSelectionModel = true;
              try {
              // This is way expensive, ListSelectionModel needs an
              // enumerator for iterating.
              int min = listSelectionModel.getMinSelectionIndex();
              int max = listSelectionModel.getMaxSelectionIndex();
              clearSelection();
              if(min != -1 && max != -1) {
                   for(int counter = min; counter <= max; counter++) {
                   if(listSelectionModel.isSelectedIndex(counter)) {
                        TreePath selPath = tree.getPathForRow
                        (counter);
                        if(selPath != null) {
                        addSelectionPath(selPath);
              finally {
              updatingListSelectionModel = false;
         * Class responsible for calling updateSelectedPathsFromSelectedRows
         * when the selection of the list changse.
         class ListSelectionHandler implements ListSelectionListener {
         public void valueChanged(ListSelectionEvent e) {
              updateSelectedPathsFromSelectedRows();

  • I18n of Swing for multilingual feature of a already displayed screen

    I have java Swing appication.Each screen has got number of buttons, labels, tool bar etc.It also have DateFormat, SimpleDateFormat, and DateFormatSymbols used for the i18n.Each screen has got a combobox listing diffrent languages.From each screen the user can select a language and that particular screen should change to this selected language.ie, suppose I have displayed the screen in English and if the user select a language french, then this particular screen should change to French.Can you please give me a way to solve this problem? My requirement are I have to iterate through each component of this container and set the labels for each component by getting the key(But I don't know how to get the key dynamically?).Then my next problem is I have used SimpleDateFormat by passing the Locale to its instantiate method.So if I am changing the language from the combobox should I have to recreate all the components in this screen? If anybody ever met this kind of requirement can you please give a sugestion or code snippet?If I know the language before showing the screen then it is OK. But converting a displayed screen to other languages....

    Hi,
    my solution is to create any GUI on JPanels and only switch between them by some central Switcher (The Frame in my example). Any GUI only must be implemented one time and you do not need any loop to change texts.
    Switching Interface:
    import java.util.Locale;
    public interface Switcher {
         public void doSwitch(Locale l);
    }Main class:
    import java.util.Locale;
    import javax.swing.JFrame;;
    public class SwitchingFrame extends JFrame implements Switcher{
         public SwitchingFrame(){
              super("Switchit");
              add(new SwitchingPanel(this));
         public void doSwitch(Locale l) {
              Locale.setDefault(l);
              getContentPane().removeAll();
              getContentPane().add(new SwitchingPanel(this));
              getContentPane().validate();
         public static void main(String args[]){
              SwitchingFrame f = new SwitchingFrame();
              f.setVisible(true);
    }GUI Panel:
    import java.awt.FlowLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.util.Locale;
    import java.util.ResourceBundle;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JPanel;
    public class SwitchingPanel extends JPanel {
         private Switcher switcher;
         public SwitchingPanel(Switcher s){
              switcher = s;
              setLayout(new FlowLayout());
              ResourceBundle b = ResourceBundle.getBundle("i18n.Texts");
              JButton b1 = new JButton(b.getString("Button1"));
              JButton b2 = new JButton(b.getString("Button2"));
              JComboBox bx = new JComboBox(new String[]{"de", "en"});
              bx.setSelectedItem(b.getString("Selection"));
              add(bx);
              bx.addItemListener(new ItemListener(){
                   public void itemStateChanged(ItemEvent e) {
                        if(e.getStateChange() == ItemEvent.SELECTED){
                             switcher.doSwitch(new Locale((String)e.getItem()));
              add(b1);
              add(b2);
    }And two Bundles for Testing:
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.ResourceBundle;
    public class Texts extends ResourceBundle {
         private HashMap<String, String> map = new HashMap<String, String>();
         public Texts(){
              map.put("Button1", "Switch");
              map.put("Button2", "Cancel");
              map.put("Selection", "en");
         @Override
         protected Object handleGetObject(String key) {
              return map.get(key);
         @Override
         public Enumeration<String> getKeys() {
              return new Enumeration <String>(){
                   Iterator <String>it = map.keySet().iterator();
                   public boolean hasMoreElements() {
                        return it.hasNext();
                   public String nextElement() {
                        return it.next();
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.ResourceBundle;
    public class Texts_de extends ResourceBundle {
         private HashMap<String, String> map = new HashMap<String, String>();
         public Texts_de(){
              map.put("Button1", "Wechseln");
              map.put("Button2", "Abbrechen");
              map.put("Selection", "de");
         @Override
         protected Object handleGetObject(String key) {
              return map.get(key);
         @Override
         public Enumeration<String> getKeys() {
              return new Enumeration <String>(){
                   Iterator <String>it = map.keySet().iterator();
                   public boolean hasMoreElements() {
                        return it.hasNext();
                   public String nextElement() {
                        return it.next();
    }hope this helps,
    Lars.

  • Can I convert an appointment to reminder

    I am still used to writing everything down as an appointment. I'm starting to use the reminder app more and more. But I often run into the problem of wanting to convert an appointment to a reminder. How can I do that?

    TX, I realised I could do this using the following after postingpublic Enumeration
    attributes()
       return new Enumeration() {
          private Iterator _keys    = _avTable.keySet().iterator();
          private String      _nextKey = null;
          public boolean hasMoreElements() {
           _nextKey = null;
           if ( _keys.hasNext() ) {
               _nextKey = (String)_keys.next();
           return (_nextKey != null);
          public Object nextElement() {
             return _nextKey;
    }Which I think does pretty much what yours does. Only trouble is now I get a ConcurrentModificationException which I didn't have b4. Ho hum, back to the API...

  • HELP me with the source code

    In this assignment you are asked to create a Java class that simulates the Java Vector class. You are also asked to create two Exception classes to allow the program to continue if errors occur. These are �MyVectNoDataException� and �MyVectIndexOutOfBoundsException�.
    1.     Write a Java class called �myVect� which will operate in the same way as the Java Vector class. In particular it should have
    a.     The following data members
    i.     An Object array
    ii.     An integer �size� that determines the size of the array
    iii.     An integer �increment� that defines the number of additional elements that will be added when the Array is to be resized.
    b.     The following methods
    i.     Constructor 1      myVect()that creates a new myVect object with an internal array size of 10 and an increment of 3.
    ii.     Constructor 2           myVect(int s)
    that creates a new myVect object with an internal array size of s and an increment of 3.
    iii.     Constructor 3           myVect(int s, int i)
    that creates a new myVect object with an internal array size of s and an increment of i.
    iv.     A method          void resize()
    that increases the size of the internal array by the number of elements in the �increment� variable.
    v.     A method      void addElement(Object o)
    that inserts an Object at the next available position in the internal array. If there are less than 3 vacant elements left in the array then the resize() method should be run automatically.
    vi.     A method      void deleteElement()
    that deletes the Object at the last occupied position in the internal array. If no element contains an Object then a MyVectNoDataException should be thrown and the program should continue.
    vii.     A method void insertElement(Object o,int p)
    that inserts an Object at position p in the internal array. The Objects at position p and below should each be moved down by one position before the insertion.
    If the index p is outside the bounds of the internal array then a MyVectIndexOutOfBoundsException should be thrown and the program should continue.
    viii.     A method void deleteElementAt(int p)
    that deletes the Object at position p in the internal array. The Objects below position p should each be moved up by one position after the deletion. If the index p is outside the bounds of the internal array then a MyVectIndexOutOfBoundsException should be thrown and the program should continue.
    If the position p is valid but does not contain an Object then a MyVectNoDataException should be thrown and the program should continue.
    ix.     A method      Object getElement()
    that returns the Object at the last occupied position in the internal array.
    x.     A method      Object getElementAt(int p)
    that returns the Object at position p in the internal array. If the index p is outside the bounds of the internal array then a MyVectIndexOutOfBoundsException should be thrown and the program should continue. If the position p is valid but does not contain an Object then a MyVectNoDataException should be thrown and the program should continue.
    xi.     A toString() method that produces a formatted String representing the myVect object and its data. It should also include the size and increment values.
    c.     Write a Java program called Assign3.java that creates a myVect object then
    i.     Store 6 objects of the following types
    1.     String
    2.     Date
    3.     Integer
    4.     String
    5.     StringTokenizer
    6.     Date
    ii.     Print the myVect object.
    iii.     Add 2 more objects
    1.     StringBuffer
    2.     Double
    iv.     Print the myVect object
    v.     Delete the Object at position 2
    vi.     Delete the Object at position 15
    vii.     Display the Object at position 10
    viii.     Display the length of the second String.
    ix.     Print the myVect object
    d.     Include Javadoc comments in the myVect class code then produce Java documentation using Javadoc.

    * @(#)MyOwnVectorReallyItIs.java     1.89 03/01/23
    * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
    * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
    package java.util;
    * The <code>MyOwnVectorReallyItIs</code> class implements a growable array of
    * objects. Like an array, it contains components that can be
    * accessed using an integer index. However, the size of a
    * <code>MyOwnVectorReallyItIs</code> can grow or shrink as needed to accommodate
    * adding and removing items after the <code>MyOwnVectorReallyItIs</code> has been created.<p>
    * Each MyOwnVectorReallyItIs tries to optimize storage management by maintaining a
    * <code>capacity</code> and a <code>capacityIncrement</code>. The
    * <code>capacity</code> is always at least as large as the MyOwnVectorReallyItIs
    * size; it is usually larger because as components are added to the
    * MyOwnVectorReallyItIs, the MyOwnVectorReallyItIs's storage increases in chunks the size of
    * <code>capacityIncrement</code>. An application can increase the
    * capacity of a MyOwnVectorReallyItIs before inserting a large number of
    * components; this reduces the amount of incremental reallocation. <p>
    * As of the Java 2 platform v1.2, this class has been retrofitted to
    * implement List, so that it becomes a part of Java's collection framework.
    * Unlike the new collection implementations, MyOwnVectorReallyItIs is synchronized.<p>
    * The Iterators returned by MyOwnVectorReallyItIs's iterator and listIterator
    * methods are <em>fail-fast</em>: if the MyOwnVectorReallyItIs is structurally modified
    * at any time after the Iterator is created, in any way except through the
    * Iterator's own remove or add methods, the Iterator will throw a
    * ConcurrentModificationException.  Thus, in the face of concurrent
    * modification, the Iterator fails quickly and cleanly, rather than risking
    * arbitrary, non-deterministic behavior at an undetermined time in the future.
    * The Enumerations returned by MyOwnVectorReallyItIs's elements method are <em>not</em>
    * fail-fast.
    * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
    * as it is, generally speaking, impossible to make any hard guarantees in the
    * presence of unsynchronized concurrent modification.  Fail-fast iterators
    * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
    * Therefore, it would be wrong to write a program that depended on this
    * exception for its correctness:  <i>the fail-fast behavior of iterators
    * should be used only to detect bugs.</i><p>
    * This class is a member of the
    * <a href="{@docRoot}/../guide/collections/index.html">
    * Java Collections Framework</a>.
    * @author  Lee Boynton
    * @author  Jonathan Payne
    * @version 1.89, 01/23/03
    * @see Collection
    * @see List
    * @see ArrayList
    * @see LinkedList
    * @since   JDK1.0
    public class MyOwnVectorReallyItIs extends AbstractList
            implements List, RandomAccess, Cloneable, java.io.Serializable
         * The array buffer into which the components of the MyOwnVectorReallyItIs are
         * stored. The capacity of the MyOwnVectorReallyItIs is the length of this array buffer,
         * and is at least large enough to contain all the MyOwnVectorReallyItIs's elements.<p>
         * Any array elements following the last element in the MyOwnVectorReallyItIs are null.
         * @serial
        protected Object elementData[];
         * The number of valid components in this <tt>MyOwnVectorReallyItIs</tt> object.
         * Components <tt>elementData[0]</tt> through
         * <tt>elementData[elementCount-1]</tt> are the actual items.
         * @serial
        protected int elementCount;
         * The amount by which the capacity of the MyOwnVectorReallyItIs is automatically
         * incremented when its size becomes greater than its capacity.  If
         * the capacity increment is less than or equal to zero, the capacity
         * of the MyOwnVectorReallyItIs is doubled each time it needs to grow.
         * @serial
        protected int capacityIncrement;
        /** use serialVersionUID from JDK 1.0.2 for interoperability */
        private static final long serialVersionUID = -2767605614048989439L;
         * Constructs an empty MyOwnVectorReallyItIs with the specified initial capacity and
         * capacity increment.
         * @param   initialCapacity     the initial capacity of the MyOwnVectorReallyItIs.
         * @param   capacityIncrement   the amount by which the capacity is
         *                              increased when the MyOwnVectorReallyItIs overflows.
         * @exception IllegalArgumentException if the specified initial capacity
         *               is negative
        public MyOwnVectorReallyItIs(int initialCapacity, int capacityIncrement) {
         super();
            if (initialCapacity < 0)
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
         this.elementData = new Object[initialCapacity];
         this.capacityIncrement = capacityIncrement;
         * Constructs an empty MyOwnVectorReallyItIs with the specified initial capacity and
         * with its capacity increment equal to zero.
         * @param   initialCapacity   the initial capacity of the MyOwnVectorReallyItIs.
         * @exception IllegalArgumentException if the specified initial capacity
         *               is negative
        public MyOwnVectorReallyItIs(int initialCapacity) {
         this(initialCapacity, 0);
         * Constructs an empty MyOwnVectorReallyItIs so that its internal data array
         * has size <tt>10</tt> and its standard capacity increment is
         * zero.
        public MyOwnVectorReallyItIs() {
         this(10);
         * Constructs a MyOwnVectorReallyItIs containing the elements of the specified
         * collection, in the order they are returned by the collection's
         * iterator.
         * @param c the collection whose elements are to be placed into this
         *       MyOwnVectorReallyItIs.
         * @throws NullPointerException if the specified collection is null.
         * @since   1.2
        public MyOwnVectorReallyItIs(Collection c) {
            elementCount = c.size();
            // 10% for growth
            elementData = new Object[
                          (int)Math.min((elementCount*110L)/100,Integer.MAX_VALUE)];
            c.toArray(elementData);
         * Copies the components of this MyOwnVectorReallyItIs into the specified array. The
         * item at index <tt>k</tt> in this MyOwnVectorReallyItIs is copied into component
         * <tt>k</tt> of <tt>anArray</tt>. The array must be big enough to hold
         * all the objects in this MyOwnVectorReallyItIs, else an
         * <tt>IndexOutOfBoundsException</tt> is thrown.
         * @param   anArray   the array into which the components get copied.
         * @throws  NullPointerException if the given array is null.
        public synchronized void copyInto(Object anArray[]) {
         System.arraycopy(elementData, 0, anArray, 0, elementCount);
         * Trims the capacity of this MyOwnVectorReallyItIs to be the MyOwnVectorReallyItIs's current
         * size. If the capacity of this MyOwnVectorReallyItIs is larger than its current
         * size, then the capacity is changed to equal the size by replacing
         * its internal data array, kept in the field <tt>elementData</tt>,
         * with a smaller one. An application can use this operation to
         * minimize the storage of a MyOwnVectorReallyItIs.
        public synchronized void trimToSize() {
         modCount++;
         int oldCapacity = elementData.length;
         if (elementCount < oldCapacity) {
             Object oldData[] = elementData;
             elementData = new Object[elementCount];
             System.arraycopy(oldData, 0, elementData, 0, elementCount);
         * Increases the capacity of this MyOwnVectorReallyItIs, if necessary, to ensure
         * that it can hold at least the number of components specified by
         * the minimum capacity argument.
         * <p>If the current capacity of this MyOwnVectorReallyItIs is less than
         * <tt>minCapacity</tt>, then its capacity is increased by replacing its
         * internal data array, kept in the field <tt>elementData</tt>, with a
         * larger one.  The size of the new data array will be the old size plus
         * <tt>capacityIncrement</tt>, unless the value of
         * <tt>capacityIncrement</tt> is less than or equal to zero, in which case
         * the new capacity will be twice the old capacity; but if this new size
         * is still smaller than <tt>minCapacity</tt>, then the new capacity will
         * be <tt>minCapacity</tt>.
         * @param minCapacity the desired minimum capacity.
        public synchronized void ensureCapacity(int minCapacity) {
         modCount++;
         ensureCapacityHelper(minCapacity);
         * This implements the unsynchronized semantics of ensureCapacity.
         * Synchronized methods in this class can internally call this
         * method for ensuring capacity without incurring the cost of an
         * extra synchronization.
         * @see java.util.MyOwnVectorReallyItIs#ensureCapacity(int)
        private void ensureCapacityHelper(int minCapacity) {
         int oldCapacity = elementData.length;
         if (minCapacity > oldCapacity) {
             Object oldData[] = elementData;
             int newCapacity = (capacityIncrement > 0) ?
              (oldCapacity + capacityIncrement) : (oldCapacity * 2);
                 if (newCapacity < minCapacity) {
              newCapacity = minCapacity;
             elementData = new Object[newCapacity];
             System.arraycopy(oldData, 0, elementData, 0, elementCount);
         * Sets the size of this MyOwnVectorReallyItIs. If the new size is greater than the
         * current size, new <code>null</code> items are added to the end of
         * the MyOwnVectorReallyItIs. If the new size is less than the current size, all
         * components at index <code>newSize</code> and greater are discarded.
         * @param   newSize   the new size of this MyOwnVectorReallyItIs.
         * @throws  ArrayIndexOutOfBoundsException if new size is negative.
        public synchronized void setSize(int newSize) {
         modCount++;
         if (newSize > elementCount) {
             ensureCapacityHelper(newSize);
         } else {
             for (int i = newSize ; i < elementCount ; i++) {
              elementData[i] = null;
         elementCount = newSize;
         * Returns the current capacity of this MyOwnVectorReallyItIs.
         * @return  the current capacity (the length of its internal
         *          data array, kept in the field <tt>elementData</tt>
         *          of this MyOwnVectorReallyItIs).
        public synchronized int capacity() {
         return elementData.length;
         * Returns the number of components in this MyOwnVectorReallyItIs.
         * @return  the number of components in this MyOwnVectorReallyItIs.
        public synchronized int size() {
         return elementCount;
         * Tests if this MyOwnVectorReallyItIs has no components.
         * @return  <code>true</code> if and only if this MyOwnVectorReallyItIs has
         *          no components, that is, its size is zero;
         *          <code>false</code> otherwise.
        public synchronized boolean isEmpty() {
         return elementCount == 0;
         * Returns an enumeration of the components of this MyOwnVectorReallyItIs. The
         * returned <tt>Enumeration</tt> object will generate all items in
         * this MyOwnVectorReallyItIs. The first item generated is the item at index <tt>0</tt>,
         * then the item at index <tt>1</tt>, and so on.
         * @return  an enumeration of the components of this MyOwnVectorReallyItIs.
         * @see     Enumeration
         * @see     Iterator
        public Enumeration elements() {
         return new Enumeration() {
             int count = 0;
             public boolean hasMoreElements() {
              return count < elementCount;
             public Object nextElement() {
              synchronized (MyOwnVectorReallyItIs.this) {
                  if (count < elementCount) {
                   return elementData[count++];
              throw new NoSuchElementException("MyOwnVectorReallyItIs Enumeration");
         * Tests if the specified object is a component in this MyOwnVectorReallyItIs.
         * @param   elem   an object.
         * @return  <code>true</code> if and only if the specified object
         * is the same as a component in this MyOwnVectorReallyItIs, as determined by the
         * <tt>equals</tt> method; <code>false</code> otherwise.
        public boolean contains(Object elem) {
         return indexOf(elem, 0) >= 0;
         * Searches for the first occurence of the given argument, testing
         * for equality using the <code>equals</code> method.
         * @param   elem   an object.
         * @return  the index of the first occurrence of the argument in this
         *          MyOwnVectorReallyItIs, that is, the smallest value <tt>k</tt> such that
         *          <tt>elem.equals(elementData[k])</tt> is <tt>true</tt>;
         *          returns <code>-1</code> if the object is not found.
         * @see     Object#equals(Object)
        public int indexOf(Object elem) {
         return indexOf(elem, 0);
         * Searches for the first occurence of the given argument, beginning
         * the search at <code>index</code>, and testing for equality using
         * the <code>equals</code> method.
         * @param   elem    an object.
         * @param   index   the non-negative index to start searching from.
         * @return  the index of the first occurrence of the object argument in
         *          this MyOwnVectorReallyItIs at position <code>index</code> or later in the
         *          MyOwnVectorReallyItIs, that is, the smallest value <tt>k</tt> such that
         *          <tt>elem.equals(elementData[k]) && (k >= index)</tt> is
         *          <tt>true</tt>; returns <code>-1</code> if the object is not
         *          found. (Returns <code>-1</code> if <tt>index</tt> >= the
         *          current size of this <tt>MyOwnVectorReallyItIs</tt>.)
         * @exception  IndexOutOfBoundsException  if <tt>index</tt> is negative.
         * @see     Object#equals(Object)
        public synchronized int indexOf(Object elem, int index) {
         if (elem == null) {
             for (int i = index ; i < elementCount ; i++)
              if (elementData==null)
              return i;
         } else {
         for (int i = index ; i < elementCount ; i++)
              if (elem.equals(elementData[i]))
              return i;
         return -1;
    * Returns the index of the last occurrence of the specified object in
    * this MyOwnVectorReallyItIs.
    * @param elem the desired component.
    * @return the index of the last occurrence of the specified object in
    * this MyOwnVectorReallyItIs, that is, the largest value <tt>k</tt> such that
    * <tt>elem.equals(elementData[k])</tt> is <tt>true</tt>;
    * returns <code>-1</code> if the object is not found.
    public synchronized int lastIndexOf(Object elem) {
         return lastIndexOf(elem, elementCount-1);
    * Searches backwards for the specified object, starting from the
    * specified index, and returns an index to it.
    * @param elem the desired component.
    * @param index the index to start searching from.
    * @return the index of the last occurrence of the specified object in this
    * MyOwnVectorReallyItIs at position less than or equal to <code>index</code> in
    * the MyOwnVectorReallyItIs, that is, the largest value <tt>k</tt> such that
    * <tt>elem.equals(elementData[k]) && (k <= index)</tt> is
    * <tt>true</tt>; <code>-1</code> if the object is not found.
    * (Returns <code>-1</code> if <tt>index</tt> is negative.)
    * @exception IndexOutOfBoundsException if <tt>index</tt> is greater
    * than or equal to the current size of this MyOwnVectorReallyItIs.
    public synchronized int lastIndexOf(Object elem, int index) {
    if (index >= elementCount)
    throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
         if (elem == null) {
         for (int i = index; i >= 0; i--)
              if (elementData[i]==null)
              return i;
         } else {
         for (int i = index; i >= 0; i--)
              if (elem.equals(elementData[i]))
              return i;
         return -1;
    * Returns the component at the specified index.<p>
    * This method is identical in functionality to the get method
    * (which is part of the List interface).
    * @param index an index into this MyOwnVectorReallyItIs.
    * @return the component at the specified index.
    * @exception ArrayIndexOutOfBoundsException if the <tt>index</tt>
    * is negative or not less than the current size of this
    * <tt>MyOwnVectorReallyItIs</tt> object.
    * given.
    * @see     #get(int)
    * @see     List
    public synchronized Object elementAt(int index) {
         if (index >= elementCount) {
         throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
    return elementData[index];
    * Returns the first component (the item at index <tt>0</tt>) of
    * this MyOwnVectorReallyItIs.
    * @return the first component of this MyOwnVectorReallyItIs.
    * @exception NoSuchElementException if this MyOwnVectorReallyItIs has no components.
    public synchronized Object firstElement() {
         if (elementCount == 0) {
         throw new NoSuchElementException();
         return elementData[0];
    * Returns the last component of the MyOwnVectorReallyItIs.
    * @return the last component of the MyOwnVectorReallyItIs, i.e., the component at index
    * <code>size() - 1</code>.
    * @exception NoSuchElementException if this MyOwnVectorReallyItIs is empty.
    public synchronized Object lastElement() {
         if (elementCount == 0) {
         throw new NoSuchElementException();
         return elementData[elementCount - 1];
    * Sets the component at the specified <code>index</code> of this
    * MyOwnVectorReallyItIs to be the specified object. The previous component at that
    * position is discarded.<p>
    * The index must be a value greater than or equal to <code>0</code>
    * and less than the current size of the MyOwnVectorReallyItIs. <p>
    * This method is identical in functionality to the set method
    * (which is part of the List interface). Note that the set method reverses
    * the order of the parameters, to more closely match array usage. Note
    * also that the set method returns the old value that was stored at the
    * specified position.
    * @param obj what the component is to be set to.
    * @param index the specified index.
    * @exception ArrayIndexOutOfBoundsException if the index was invalid.
    * @see #size()
    * @see List
    * @see     #set(int, java.lang.Object)
    public synchronized void setElementAt(Object obj, int index) {
         if (index >= elementCount) {
         throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                  elementCount);
         elementData[index] = obj;
    * Deletes the component at the specified index. Each component in
    * this MyOwnVectorReallyItIs with an index greater or equal to the specified
    * <code>index</code> is shifted downward to have an index one
    * smaller than the value it had previously. The size of this MyOwnVectorReallyItIs
    * is decreased by <tt>1</tt>.<p>
    * The index must be a value greater than or equal to <code>0</code>
    * and less than the current size of the MyOwnVectorReallyItIs. <p>
    * This method is identical in functionality to the remove method
    * (which is part of the List interface). Note that the remove method
    * returns the old value that was stored at the specified position.
    * @param index the index of the object to remove.
    * @exception ArrayIndexOutOfBoundsException if the index was invalid.
    * @see #size()
    * @see     #remove(int)
    * @see     List
    public synchronized void removeElementAt(int index) {
         modCount++;
         if (index >= elementCount) {
         throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                  elementCount);
         else if (index < 0) {
         throw new ArrayIndexOutOfBoundsException(index);
         int j = elementCount - index - 1;
         if (j > 0) {
         System.arraycopy(elementData, index + 1, elementData, index, j);
         elementCount--;
         elementData[elementCount] = null; /* to let gc do its work */
    * Inserts the specified object as a component in this MyOwnVectorReallyItIs at the
    * specified <code>index</code>. Each component in this MyOwnVectorReallyItIs with
    * an index greater or equal to the specified <code>index</code> is
    * shifted upward to have an index one greater than the value it had
    * previously. <p>
    * The index must be a value greater than or equal to <code>0</code>
    * and less than or equal to the current size of the MyOwnVectorReallyItIs. (If the
    * index is equal to the current size of the MyOwnVectorReallyItIs, the new element
    * is appended to the MyOwnVectorReallyItIs.)<p>
    * This method is identical in functionality to the add(Object, int) method
    * (which is part of the List interface). Note that the add method reverses
    * the order of the parameters, to more closely match array usage.
    * @param obj the component to insert.
    * @param index where to insert the new component.
    * @exception ArrayIndexOutOfBoundsException if the index was invalid.
    * @see #size()
    * @see     #add(int, Object)
    * @see     List
    public synchronized void insertElementAt(Object obj, int index) {
         modCount++;
         if (index > elementCount) {
         throw new ArrayIndexOutOfBoundsException(index
                                  + " > " + elementCount);
         ensureCapacityHelper(elementCount + 1);
         System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
         elementData[index] = obj;
         elementCount++;
    * Adds the specified component to the end of this MyOwnVectorReallyItIs,
    * increasing its size by one. The capacity of this MyOwnVectorReallyItIs is
    * increased if its size becomes greater than its capacity. <p>
    * This method is identical in functionality to the add(Object) method
    * (which is part of the List interface).
    * @param obj the component to be added.
    * @see     #add(Object)
    * @see     List
    public synchronized void addElement(Object obj) {
         modCount++;
         ensureCapacityHelper(elementCount + 1);
         elementData[elementCount++] = obj;
    * Removes the first (lowest-indexed) occurrence of the argument
    * from this MyOwnVectorReallyItIs. If the object is found in this MyOwnVectorReallyItIs, each
    * component in the MyOwnVectorReallyItIs with an index greater or equal to the
    * object's index is shifted downward to have an index one smaller
    * than the value it had previously.<p>
    * This method is identical in functionality to the remove(Object)
    * method (which is part of the List interface).
    * @param obj the component to be removed.
    * @return <code>true</code> if the argument was a component of this
    * MyOwnVectorReallyItIs; <code>false</code> otherwise.
    * @see     List#remove(Object)
    * @see     List
    public synchronized boolean removeElement(Object obj) {
         modCount++;
         int i = indexOf(obj);
         if (i >= 0) {
         removeElementAt(i);
         return true;
         return false;
    * Removes all components from this MyOwnVectorReallyItIs and sets its size to zero.<p>
    * This method is identical in functionality to the clear method
    * (which is part of the List interface).
    * @see     #clear
    * @see     List
    public synchronized void removeAllElements() {
    modCount++;
         // Let gc do its work
         for (int i = 0; i < elementCount; i++)
         elementData[i] = null;
         elementCount = 0;
    * Returns a clone of this MyOwnVectorReallyItIs. The copy will contain a
    * reference to a clone of the internal data array, not a reference
    * to the original internal data array of this <tt>MyOwnVectorReallyItIs</tt> object.
    * @return a clone of this MyOwnVectorReallyItIs.
    public synchronized Object clone() {
         try {
         MyOwnVectorReallyItIs v = (MyOwnVectorReallyItIs)super.clone();
         v.elementData = new Object[elementCount];
         System.arraycopy(elementData, 0, v.elementData, 0, elementCount);
         v.modCount = 0;
         return v;
         } catch (CloneNotSupportedException e) {
         // this shouldn't happen, since we are Cloneable
         throw new InternalError();
    * Returns an array containing all of the elements in this MyOwnVectorReallyItIs
    * in the correct order.
    * @since 1.2
    public synchronized Object[] toArray() {
         Object[] result = new Object[elementCount];
         System.arraycopy(elementData, 0, result, 0, elementCount);
         return result;
    * Returns an array containing all of the elements in this MyOwnVectorReallyItIs in the
    * correct order; the runtime type of the returned array is that of the
    * specified array. If the MyOwnVectorReallyItIs fits in the specified array, it is
    * returned therein. Otherwise, a new array is allocated with the runtime
    * type of the specified array and the size of this MyOwnVectorReallyItIs.<p>
    * If the MyOwnVectorReallyItIs fits in the specified array with room to spare
    * (i.e., the array has more elements than the MyOwnVectorReallyItIs),
    * the element in the array immediately following the end of the
    * MyOwnVectorReallyItIs is set to null. This is useful in determining the length
    * of the MyOwnVectorReallyItIs <em>only</em> if the caller knows that the MyOwnVectorReallyItIs
    * does not contain any null elements.
    * @param a the array into which the elements of the MyOwnVectorReallyItIs are to
    *          be stored, if it is big enough; otherwise, a new array of the
    *           same runtime type is allocated for this purpose.
    * @return an array containing the elements of the MyOwnVectorReallyItIs.
    * @exception ArrayStoreException the runtime type of a is not a supertype
    * of the runtime type of every element in this MyOwnVectorReallyItIs.
    * @throws NullPointerException if the given array is null.
    * @since 1.2
    public synchronized Object[] toArray(Object a[]) {
    if (a.length < elementCount)
    a = (Object[])java.lang.reflect.Array.newInstance(
    a.getClass().getComponentType(), elementCount);
         System.arraycopy(elementData, 0, a, 0, elementCount);
    if (a.length > elementCount)
    a[elementCount] = null;
    return a;
    // Positional Access Operations
    * Returns the element at the specified position in this MyOwnVectorReallyItIs.
    * @param index index of element to return.
    * @return object at the specified index
    * @exception ArrayIndexOutOfBoundsException index is out of range (index
    *           < 0 || index >= size()).
    * @since 1.2
    public synchronized Object get(int index) {
         if (index >= elementCount)
         throw new ArrayIndexOutOfBoundsException(index);
         return elementData[index];
    * Replaces the element at the specified position in this MyOwnVectorReallyItIs with the
    * specified element.
    * @param index index of element to replace.
    * @param element element to be stored at the specified position.
    * @return the element previously at the specified position.
    * @exception ArrayIndexOutOfBoundsException index out of range
    *          (index < 0 || index >= size()).
    * @since 1.2
    public synchronized Object set(int index, Object element) {
         if (index >= elementCount)
         throw new ArrayIndexOutOfBoundsException(index);
         Object oldValue = elementData[index];
         elementData[index] = element;
         return oldValue;
    * Appends the specified element to the end of this MyOwnVectorReallyItIs.
    * @param o element to be appended to this MyOwnVectorReallyItIs.
    * @return true (as per the general contract of Collection.add).
    * @since 1.2
    public synchronized boolean add(Object o) {
         modCount++;
         ensureCapacityHelper(elementCount + 1);
         elementData[elementCount++] = o;
    return true;
    * Removes the first occurrence of the specified element in this MyOwnVectorReallyItIs
    * If the MyOwnVectorReallyItIs does not contain the element, it is unchanged. More
    * formally, removes the element with the lowest index i such that
    * <code>(o==null ? get(i)==null : o.equals(get(i)))</code> (if such
    * an element exists).
    * @param o element to be removed from this MyOwnVectorReallyItIs, if present.
    * @return true if the MyOwnVectorReallyItIs contained the specified element.
    * @since 1.2
    public boolean remove(Object o) {
    return removeElement(o);
    * Inserts the specified element at the specified position in this MyOwnVectorReallyItIs.
    * Shifts the element currently at that position (if any) and any
    * subsequent elements to the right (adds one to their indices).
    * @param index index at which the specified element is to be inserted.
    * @param

  • Does vector reduces performance

    Hi,
    it is said that vector is serializable and thread safe
    so it is slow
    ny doubt is if we declare and use vector in a local method then it is not shared with others does still the fact that vector is serializable reduces performance
    is using arraylist better
    i have seen code of many people using vectors
    if vectors are not to be used we have to be careful
    about vectors is using arraylist better than vector
    for same functionality or which is better to use
    if requirement is to store string array which can
    extend to any number of items

    Hi,
    Vectors are extremely slow, due to it being synchronized. An ArrayList is a lot faster than a Vector, but if possible, I'd look at just a plain old array. Arrays are extremely faster than both ArrayList or a Vector. The problem is that arrays don't automatically resize. So it really depends on your design. If you do end up going with a Vector, don't use an Enumeration of Iterator to iterate over the Vector. A lot of unnecessary objects are created, etc... Get the size of the vector at use a simple loop, which is more compact and quicker....
    /rick

  • Must be caught or declared to be thrown ! Help !

    Dear Java People,
    I have only one error in my program in the TryVectorAndSort class
    "Unreported exception (InvalidUserInputException)
    Must be caught or declared to be thrown lines 41,49"
    >>    String firstName = in.readString().trim();
    >>     String lastName = in.readString().trim();
    so the error in the above 2 lines points to the readString() method
    which is below
      public String readString() throws InvalidUserInputException
           if(readToken() == tokenizer.TT_WORD || ttype == '\"' ||  ttype == '\'')
            return tokenizer.sval;
           else
             throw new InvalidUserInputException(" readString() failed. " + " Input data is not a string");
    below is the entire FormattedInput class
    Thank you in advance
    Norman
    import java.io.*;
    import java.util.*;
    public class FormattedInput
        // Method to read an int value
        public int readInt()
          for(int i = 0; i < 2; i++)
          if(readToken() == tokenizer.TT_NUMBER)
            return (int)tokenizer.nval;   // value is numeric so return as int
          else
            System.out.println("Incorrect input: " + tokenizer.sval +
               " Re-enter as integer");
            continue;         //retry the read operation
          }  //end of if statement
          System.out.println("Five failures reading an int value" + " - program terminated");
          System.exit(1);  // end the program
          return 0;
        } //end of method
         public double readDouble() throws InvalidUserInputException
           if(readToken() != tokenizer.TT_NUMBER)
              throw new InvalidUserInputException(" readDouble() failed. " + " Input data not numeric");
           return tokenizer.nval;
         public String readString() throws InvalidUserInputException
           if(readToken() == tokenizer.TT_WORD || ttype == '\"' ||  ttype == '\'')
            return tokenizer.sval;
           else
             throw new InvalidUserException(" readString() failed. " + " Input data is not a string");
           //helper method to read the next token
           private int readToken()
             try
               ttype = tokenizer.nextToken();
               return ttype;
             catch(IOException e)
               e.printStackTrace(System.err);
               System.exit(1);
              return 0;
           //object to tokenize input from the standard input stream
           private StreamTokenizer tokenizer = new StreamTokenizer(
                                                new BufferedReader(
                                                 new InputStreamReader(System.in)));
           private int ttype;                  //stores the token type code
    import java.io.*;
    import java.util.*;
    public class TryVectorAndSort
         public static void main(String[] args)
        Person aPerson;           // a Person object
        Crowd filmCast = new Crowd();
        //populate the crowd
        for( ; ;)
          aPerson = readPerson();
          if(aPerson == null)
            break;   // if null is obtained we break out of the for loop
          filmCast.add(aPerson);
        int count = filmCast.size();
        System.out.println("You added " + count + (count == 1 ? " person":  " people ") + "to the cast.\n");
        //Show who is in the cast using an iterator
         Iterator myIter = filmCast.iterator();
        //output all elements
        while(myIter.hasNext() )
          System.out.println(myIter.next());
        }//end of main
          //read a person from the keyboard
          static public Person readPerson()
         FormattedInput in = new FormattedInput();
            //read in the first name and remove blanks front and back
            System.out.println("\nEnter first name or ! to end:");
            String firstName = in.readString().trim(); //read and trim a string
            //check for a ! entered. If so we are done
            if(firstName.charAt(0) == '!')
              return null;
            //read the last name also trimming the blanks
            System.out.println("Enter last name:");
            String lastName = in.readString().trim();    // read and trim a string
            return new Person(firstName, lastName);
    //when I ran the program the output I received was:
    import java.io.StreamTokenizer;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    public class InvalidUserInputException extends Exception
       public InvalidUserInputException() { }
          public InvalidUserInputException(String message)
              super(message);
    public class Person implements Comparable
      public Person(String firstName, String lastName)
        this.firstName = firstName;
        this.lastName = lastName;
      public String toString()
        return firstName + "  " + lastName;
       //Compare Person objects
        public int compareTo(Object person)
           int result = lastName.compareTo(((Person)person).lastName);
           return result == 0 ? firstName.compareTo(((Person)person).firstName):result;
      private String firstName;
      private String lastName;
    import java.util.*;
    class Crowd
      public Crowd()
        //Create default Vector object to hold people
         people = new Vector();
      public Crowd(int numPersons)
        //create Vector object to hold  people with given capacity
         people = new Vector(numPersons);
        //add a person to the crowd
        public boolean add(Person someone)
          return people.add(someone);
         //get the person at the given index
          Person get(int index)
          return (Person)people.get(index);
         //get the numbers of persons in the crowd
          public int size()
            return people.size();
          //get  people store capacity
          public int capacity()
            return people.capacity();
          //get a listIterator for the crowd
          public Iterator iterator()
            return people.iterator();
            //A Vector implements the List interface (that has the static sort() method
            public void sort()
              Collections.sort(people);
          //Person store - only accessible through methods of this class
          private Vector people;
    }

    Dear Levi H,
    When I changed the catch block type to
    String lastName= "";
    try
    lastName = in.readString().trim(); //read and trim a string
    catch(InvalidUserInputException e)
    e.printStackTrace(System.err);
    I no longer have errors in the driver class but in the FormattedInput
    class there are new errors that say:
    "FormattedInput.java": Error #: 204 : illegal start of expression at line 49,68
    "FormattedInput.java": Error #: 206 : malformed expression at line 39,49
    Help !
    Norman

Maybe you are looking for

  • How we can Reverse the closed Production Order (REVERSAL)

    Dear All How we can Reverse the Closed  Production Order Which one is confirmed before 5 or 6 month ..Actually i want to reverse the production order  with old pricing.Not with present pricing. Rgds Pankaj Agarwal

  • Data Source ID must be of type IDataSource

    I'm trying to do a report with a chart in it (I don't know if the fact that it has a chart makes any difference), and I'm getting the following error where the chart should appear: The DataSourceID of the ReportDataSource 'DataSetD' of the ReportView

  • White marker not following when audio plays

    When I playback audio, the tracker (white line -not sure what it's called) does not go along with where the audio should be. This is usually the case, though I must say that every once in a while it does. It seems to help when I'm zoomed in closer. I

  • Bridge or extend network using Apple TC & Extreme?

    I have the following setup: Uverse router (wifi off) -> Apple Time Capsule (creating wireless) -> Imac through ethernet From the TC, there is a powerline adapter, which on the other end connects to a 4 port hub and other ethernet devices. Accessing a

  • Reload flash document

    This is a stupid question but I have looked everything, how would you reload a swf document. I want to do this so it reimports external data. I can figure that out but not this... go figure :) Thought it wold be something like: this.reload(); But thi