TableSorter throws ArrayIndexOutOfBoundsException

Hi,
When I'm using the TableSorter in my program the getValueAt(int, int) throws ArrayIndexOutOfBoundsException.
I can't understand why??
My only idea is that the model isn't informed of a change in size of the data.
All clues are welcome!!
/David

Hi,
use fireTableRowsDeleted(...)-method, every time, you delete one or more rows
use fireTableStructureChanged()-method, every time, you delete a hole column in the model
This will inform the JTable correctly, if the table decreases in size in any direction.
greetings Marsian

Similar Messages

  • ResourceBundle.getString() throws ArrayIndexOutOfBoundsException

    Hi Everyone.
    I am getting "java.lang.ArrayIndexOutOfBoundsException: 1" when I try to call ResourceBundle.getString():
    ResourceBundle rb = ResourceBundle.getBundle("full.package.name.StringsBundle");
    String s;
    try {
        s = rb.getString( key_that_i_am_pretty_sure_really_exists_in_StringsBundle_and_is_really_a_string );
    } catch ( Exception e ) {
        s = "Exception:" + e.toString();
    }s always ends up as "Exception: java.lang.ArrayIndexOutOfBoundsException: 1"
    According to the javadoc, getString() can throw NullPointerExceptions or MissingResourceExceptions or ClassCastException, but not ArrayIndexOutOfBoundsExceptions... and the Exception doesn't make any sense to me in this context...
    Could this be a bug in the ResourceBundle implementation? Or is there something really stupid I am missing or what do you think?
    Thanks,
    Bishop

    Thanks for the lead about the character compatibility. I will look into that more. It sounds likely since the strings I am trying to look up in the bundle have kanji in them.
    Here's the stack trace (some package/class/variable names slightly obfuscated). The rogue exception is indeed being thrown by the ListResourceBundle implementation code.
    java.lang.ArrayIndexOutOfBoundsException: 1
            at java.util.ListResourceBundle.loadLookup(ListResourceBundle.java:176)
            at java.util.ListResourceBundle.handleGetObject(ListResourceBundle.java:106)
            at java.util.ResourceBundle.getObject(ResourceBundle.java:378)
            at java.util.ResourceBundle.getString(ResourceBundle.java:344)
            at my.app.package.MyOtherObject.getStringByKey(MyOtherObject.java:59)
            at my.app.package.MyCommandObject.execute(MyCommandObject.java:79)
            at my.app.package.MyServletObject.processRequest(MyServletObject.java:102)
            at my.app.package.MyServletObject.doPost(MyServletObject.java:131)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
            at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:427)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:315)
            at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:287)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:218)
            at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
            at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
            at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:94)
            at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:98)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:222)
            at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
            at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
            at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:587)
            at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1096)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:166)
            at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
            at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
            at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:587)
            at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1096)
            at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:288)
            at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.invokeAdapter(DefaultProcessorTask.java:647)
            at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:579)
            at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.process(DefaultProcessorTask.java:831)
            at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.executeProcessorTask(DefaultReadTask.java:341)
            at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:263)
            at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:214)
            at com.sun.enterprise.web.portunif.PortUnificationPipeline$PUTask.doTask(PortUnificationPipeline.java:380)
            at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:265)
            at com.sun.enterprise.web.connector.grizzly.ssl.SSLWorkerThread.run(SSLWorkerThread.java:106)

  • Long.toString(long, int) throws ArrayIndexOutOfBoundsException

    We're using Long.toString(long, int) to convert a long into a base-32 string, which is used as a primary key for entities in our database. On occasion, Long.toString(long, int) throws an ArrayOutOfBoundsException! This only occurs in the deployed system, I cannot get it to occur in a testing environment.
    The object that contains the call to Long.toString(int, long) is shared by multiple threads, but the state of the object is immutable and access to the object is not synchronized. I have tested this code extensively with multithreaded access and cannot reproduce the exception in a test environment.
    Furthermore, this bug only occurs on Linux.
    As a workaround, we have a loop that will attempt the call 5 times, and then fail if the call could not be completed. Generally, this helps to get the code running but will sometimes fail.
    Here are some characteristics of the problem:
    1) Linux kernel 2.4.10 on Pentium III.
    2) Sun JVM 1.3.1_01
    3) Code is accessed from a session bean deployed into JBoss 2.4.3.
    4) Database entities have undergone bytecode enhancement per JDO specification.
    Obviously, the bytecode enhancement is most suspect here. The class that contains the error-prone code is not enhanced, but entities do contain references to instances of the primary key class.
    At first blush this sounds like a classic memory corruption issue that is surfacing in Long.toString() but is probably caused elsewhere. Has anybody seen anything like this or know of either a solution or suggested debugging procedure?
    Thanks.
    -brian

    We already discussed that approach. The reason that
    it was rejected is because my C experience suggests
    that it will just move the corruption evidence to another
    area of the application with possibly more insidious
    effects.I'm not so sure about that. Does your five-try loop actually help? If a stateless method throws an IndexOutOfBoundsException with a given set of parameters, then I would expect it to always throw this exception with the same parameters. Any other behaviour is non-deterministic and not suitable (IMHO) for a production machine.
    I assume you are manipulating arrays in other locations of your code... if these other locations aren't displaying similar non-deterministic behaviour, then common sense dictates that writing your own toString method will not exhibit the same non-deterministic behaviour.
    A little test, compile a class (TestLong, for argument sake) with the method exactly from the Sun source. Decompile it to byte-code with 'javap -c TestLong', and compare that to the same method from Long with 'javap -c java.lang.Long'. If the bytecode isn't identical (Barring numbering differences for class reference table differences), then the implementation you have is not the expected.
    A final suggestion, try a different JVM - both IBM and Sun provide JVMs for linux?

  • ArrayIndexOutOfBoundsException in JDeveloper

    Hi,
    I am working with JDeveloper for 11.5.10 CU2. I extended a View object for an LOV and created the relevant substitution for it.
    It was working fine and when I had to create another substitution it did not allow me to go ahead.
    On the click of the the Substitutions Tab in the Edit Business Components Project window I get the following error:
    java.lang.ArrayIndexOutOfBoundsException
         at oracle.jbo.dt.ui.main.tree.DtuTreeNode.getChildAt(DtuTreeNode.java:109)
         at javax.swing.tree.DefaultTreeModel.nodesWereInserted(DefaultTreeModel.java:293)
         at javax.swing.tree.DefaultTreeModel.insertNodeInto(DefaultTreeModel.java:223)
         at oracle.jbo.dt.ui.main.tree.DtuBaseTree.addChild(DtuBaseTree.java:142)
         at oracle.jbo.dt.ui.main.tree.DtuJboTree.addChild(DtuJboTree.java:472)
         at oracle.jbo.dt.ui.main.tree.DtuJboTree.populateObject(DtuJboTree.java:465)
         at oracle.jbo.dt.ui.main.tree.DtuJboTree.populateContainerChildren(DtuJboTree.java:429)
         at oracle.jbo.dt.ui.main.tree.DtuJboTree.populateFromContainer(DtuJboTree.java:393)
         at oracle.jbo.dt.ui.main.tree.DtuJboTree.populateContainerChildren(DtuJboTree.java:414)
         at oracle.jbo.dt.ui.main.tree.DtuJboTree.populateTree(DtuJboTree.java:362)
         at oracle.jbo.dt.ui.main.tree.DtuJboTree.setApplication(DtuJboTree.java:118)
         at oracle.jbo.dt.ui.pkg.PKSubsPanel.enter(PKSubsPanel.java:169)
         at oracle.jbo.dt.ui.main.dlg.DtuWizard.selectPage(DtuWizard.java:620)
         at oracle.jbo.dt.ui.pkg.PKAppWizard.selectPage(PKAppWizard.java:258)
         at oracle.jbo.dt.ui.main.dlg.DtuWizard.selectPage(DtuWizard.java:595)
         at oracle.jbo.dt.ui.main.dlg.DtuWizard.newMddPageSelected(DtuWizard.java:633)
         at oracle.jbo.dt.ui.main.dlg.DtjMddTraversable.onEntry(DtuMddNavigable.java:255)
         at oracle.ide.panels.MDDPanel.enterTraversableImpl(MDDPanel.java:649)
         at oracle.ide.panels.MDDPanel.enterTraversable(MDDPanel.java:630)
         at oracle.ide.panels.MDDPanel.access$7000571(MDDPanel.java:86)
         at oracle.ide.panels.MDDPanel$Tsl.updateSelectedNavigable(MDDPanel.java:933)
         at oracle.ide.panels.MDDPanel$Tsl.actionPerformed(MDDPanel.java:803)
         at javax.swing.Timer.fireActionPerformed(Timer.java:271)
         at javax.swing.Timer$DoPostEvent.run(Timer.java:201)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:454)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:141)
         at java.awt.Dialog$1.run(Dialog.java:540)
         at java.awt.Dialog.show(Dialog.java:561)
         at java.awt.Component.show(Component.java:1133)
         at java.awt.Component.setVisible(Component.java:1088)
         at oracle.jbo.dt.ui.main.dlg.DtjDialog.setVisible(DtjDialog.java:137)
         at oracle.jbo.dt.ui.main.dlg.DtjMddWizardDialog.setVisible(DtuWizard.java:1922)
         at oracle.bali.ewt.dialog.JEWTDialog.runDialog(Unknown Source)
         at oracle.jbo.dt.ui.main.dlg.DtjDialog.showDialog(DtjDialog.java:115)
         at oracle.jbo.dt.ui.main.dlg.DtjMddWizardDialog.showDialog(DtuWizard.java:1881)
         at oracle.jbo.dt.ui.main.dlg.DtuWizard.createMddWizard(DtuWizard.java:422)
         at oracle.jbo.dt.ui.main.dlg.DtuWizard.setVisible(DtuWizard.java:276)
         at oracle.jbo.dt.ui.main.dlg.DtuWizard.showDialog(DtuWizard.java:254)
         at oracle.jbo.dt.jdevx.ui.JdxMenuManager.invokePackageWizard(JdxMenuManager.java:877)
         at oracle.jbo.dt.jdevx.ui.JdxMenuManager.invokePackageWizard(JdxMenuManager.java:854)
         at oracle.jbo.dt.ui.main.DtuMenuManager.doEditMenuAction(DtuMenuManager.java:1150)
         at oracle.jbo.dt.ui.main.DtuMenuManager.doMenuAction(DtuMenuManager.java:1006)
         at oracle.jbo.dt.jdevx.ui.JdxMenuManager.doMenuAction(JdxMenuManager.java:533)
         at oracle.jbo.dt.ui.main.DtuMenuManager.doAction(DtuMenuManager.java:838)
         at oracle.jbo.dt.ui.main.DtuMenuManager.doAction(DtuMenuManager.java:823)
         at oracle.jbo.dt.jdevx.ui.JdxMenuManager.doActionPerformed(JdxMenuManager.java:391)
         at oracle.jbo.dt.jdevx.ui.JdxMenuInvoker.run(JdxMenuManager.java:1076)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:454)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
    I tried restarting JDeveloper but it still persists. Any help in this regard would be appreciated.
    Warm Regards,
    Jasmine.

    public WizardPage getPageAt(int index)
    Returns a page by index.
    Parameters:
    index - the page index
    Throws:
    ArrayIndexOutOfBoundsException - If an invalid index was given
    Try to check your implementation before the error existed. If you think the code is correct try to CLEAN your project (I mean, go to RUN then select clean). Then try to recompile. Sometimes intermittent errors appears when your code is not clean.
    TIP:
    * In JDEV the XML file (PageDef) is updated automatically, try to look at those files because there are times when you remove something, the XML is not properly updated (you have to clean it manually sometimes in explorer).
    *The code is autogenerated when you add something, right. Sometimes the arrangement of code affects the output.
    I hope this can help you somehow. God bless.
    Cykun

  • Rutime error: ArrayIndexOutOfBoundsException -- though i'm using a vector!!

    hello,
    here is my situation,
    I have a vector in which u find classes' names in the following order:
    v.get[0] contains a class name
    v.get[1] contains a class that inherits from v.get[0]
    v.get[2] contains a class( it may b the same as v.get[0] or v.get[1])
    v.get[3] contains a class that inherits from v.get[2]
    etc....
    so I have to write a code that draws me the tree inheritance( I can have many trees so i have to find first the different roots)
    here is the code i wrote but i still have an error at runtime and i hope u can help me
    import java.util.*;
    public class DrawClasses{
    public static void main(String args[]){
    draw();
    public static void draw() throws ArrayIndexOutOfBoundsException{
    String s="";
    int sum=0;
    Vector< String > v = new Vector< String >();
    Vector< String > v1 = new Vector< String >();
    Vector< String > v2 = new Vector< String >();
    v.add("A");// A is the first root
    v.add("B");
    v.add("A");
    v.add("C");
    v.add("A");
    v.add("D");
    v.add("B");
    v.add("E");
    v.add("B");
    v.add("F");
    v.add("B");
    v.add("G");
    v.add("C");
    v.add("H");
    v.add("C");
    v.add("I");
    v.add("D");
    v.add("J");
    v.add("G");
    v.add("K");
    v.add("G");
    v.add("L");
    v.add("I");
    v.add("M");
    v.add("Z");// Z is the other root
    v.add("O");
    v.add("Z");
    v.add("P");
    for(int i=0; i<v.size(); i++) //get distinct classes and fill them in vector v1
       if( v1.contains(v.get(i))){}
       else {v1.add(v.get(i));}
    for(int i=0;i<v1.size();i++)//get root classes and fill them in vector v2
       for(int j=0;j<v.size();j++)
         if (v.get(j).equals(v1.get(i)))
            if(j%2!=0){sum=sum+1; }
       if(sum==0)
          {v2.add(v1.get(i));}
          sum=0;
    for(int i=0;i<=v1.size();i++) // get the tree for each root class
      if(v2.contains(v1.get(i)))
        System.out.println(v1.get(i)+" is root");
        for(int j=0;j<=v1.size();j++)
           for(int k=0;k<v.size();k++)
             if(v1.get(j)==v.get(k) && k%2==0)
                if(v2.contains(v1.get(j)) && !v1.get(j).equals(v1.get(i))){} else
                System.out.println(v.get(k+1)+" inherits from "+v1.get(j));
    //ListIterator iter = v2.listIterator();
    //while (iter.hasNext()) {
        //System.out.println((String)iter.next());}
    NB:the runtime gives me the output only for one tree and then it gives me the error at runtime
    Thank you

    But if you had been programming in Java (instead of bastardized C) you wouldn't have had that problem. Instead of this:
    for(int i=0; i<v.size(); i++) //get distinct classes and fill them in vector v1
      if( v1.contains(v.get(i))){}
      else {v1.add(v.get(i));}
    }you could write this:
    for (String s: v) {
      if ( ! v1.contains(s)) {
        v1.add(s);
    }This does bring up the question about why you don't just use a Set if you want to store only distinct entries. And there's the question of why you're using the obsolete Vector class. But let's leave it there for now.

  • How to resolve ArrayIndexOutOfBoundsException

    Hello,
    I've an issue in running a program which throws ArrayIndexOutOfBoundsException. The program tries to insert many records in multiple tables. Sometime it works fine without any issue and sometime it fail. I believe that its because of the data what I select to trigger the event.
    I have 2 set of data which trigger an event for the insertion of records. The both dataset are same. Using the first one it works fine and using the second it give me an Exception ArrayIndexOutOfBoundsException.
    Please find the Stack Trace from the Logs of the event which ended up in failure. Please someone help me try to understand why its failing.
    2010-04-15 14:35:26,981 [WebContainer : 10] ERROR DS-UTIL - ERROR: class java.lang.ArrayIndexOutOfBoundsException Exception caught during insert: -32393
    java.lang.ArrayIndexOutOfBoundsException: -32393
    at oracle.jdbc.driver.OraclePreparedStatement.setupBindBuffers(OraclePreparedStatement.java:2673)
    at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10689)
    at com.ibm.ws.rsadapter.jdbc.WSJdbcPreparedStatement.pmiExecuteBatch(WSJdbcPreparedStatement.java:958)
    at com.ibm.ws.rsadapter.jdbc.WSJdbcStatement.executeBatch(WSJdbcStatement.java:705)
    at com.labvantage.sapphire.DataSetUtil.insert(DataSetUtil.java:191)
    at com.labvantage.sapphire.actions.sdidata.AddDataSet.processAction(AddDataSet.java:361)
    at sapphire.action.BaseAction.processAction(BaseAction.java:81)
    at com.labvantage.sapphire.services.ActionService.processActionClass(ActionService.java:371)
    at com.labvantage.sapphire.services.ActionService.processAction(ActionService.java:256)
    at com.labvantage.sapphire.services.ActionService.processAction(ActionService.java:178)
    at com.labvantage.sapphire.actions.workitem.AddSDIWorkItem.applyWorkItemItem(AddSDIWorkItem.java:595)
    at com.labvantage.sapphire.actions.workitem.AddSDIWorkItem.applyWorkItem(AddSDIWorkItem.java:519)
    at com.labvantage.sapphire.actions.workitem.AddSDIWorkItem.processAction(AddSDIWorkItem.java:379)
    at com.labvantage.sapphire.actions.workitem.AddSDIWorkItem.processAction(AddSDIWorkItem.java:223)
    at sapphire.action.BaseAction.processAction(BaseAction.java:81)
    at com.labvantage.sapphire.services.ActionService.processActionClass(ActionService.java:371)
    Thanks in advance!!

    Hello,
    I've an issue in running a program which throws ArrayIndexOutOfBoundsException. The program tries to insert many records in multiple tables. Sometime it works fine without any issue and sometime it fail. I believe that its because of the data what I select to trigger the event.
    I have 2 set of data which trigger an event for the insertion of records. The both dataset are same. Using the first one it works fine and using the second it give me an Exception ArrayIndexOutOfBoundsException.
    Please find the Stack Trace from the Logs of the event which ended up in failure. Please someone help me try to understand why its failing.
    2010-04-15 14:35:26,981 [WebContainer : 10] ERROR DS-UTIL - ERROR: class java.lang.ArrayIndexOutOfBoundsException Exception caught during insert: -32393
    java.lang.ArrayIndexOutOfBoundsException: -32393
    at oracle.jdbc.driver.OraclePreparedStatement.setupBindBuffers(OraclePreparedStatement.java:2673)
    at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10689)
    at com.ibm.ws.rsadapter.jdbc.WSJdbcPreparedStatement.pmiExecuteBatch(WSJdbcPreparedStatement.java:958)
    at com.ibm.ws.rsadapter.jdbc.WSJdbcStatement.executeBatch(WSJdbcStatement.java:705)
    at com.labvantage.sapphire.DataSetUtil.insert(DataSetUtil.java:191)
    at com.labvantage.sapphire.actions.sdidata.AddDataSet.processAction(AddDataSet.java:361)
    at sapphire.action.BaseAction.processAction(BaseAction.java:81)
    at com.labvantage.sapphire.services.ActionService.processActionClass(ActionService.java:371)
    at com.labvantage.sapphire.services.ActionService.processAction(ActionService.java:256)
    at com.labvantage.sapphire.services.ActionService.processAction(ActionService.java:178)
    at com.labvantage.sapphire.actions.workitem.AddSDIWorkItem.applyWorkItemItem(AddSDIWorkItem.java:595)
    at com.labvantage.sapphire.actions.workitem.AddSDIWorkItem.applyWorkItem(AddSDIWorkItem.java:519)
    at com.labvantage.sapphire.actions.workitem.AddSDIWorkItem.processAction(AddSDIWorkItem.java:379)
    at com.labvantage.sapphire.actions.workitem.AddSDIWorkItem.processAction(AddSDIWorkItem.java:223)
    at sapphire.action.BaseAction.processAction(BaseAction.java:81)
    at com.labvantage.sapphire.services.ActionService.processActionClass(ActionService.java:371)
    Thanks in advance!!

  • Which IndexOutOfBoundsException to throw and why?

    I'm looking into FilterOutputStream implementation :
        public void write(byte b[], int off, int len) throws IOException {
            if ((off | len | (b.length - (len + off)) | (off + len)) < 0)
                throw new IndexOutOfBoundsException();
            for (int i = 0 ; i < len ; i++) {
                write(b[off + i]);
        }Can you explain the explicit range check above? I thought system performs boundry checking automatically throwing ArrayIndexOutOfBoundsException. I'm interested in the considerations overriding the method.

    If ArrayIndexOutOfBoundsException were thrown from that method, it would be because of an internal implementation error of the method itself. That's an implementation detail that the caller of the API should not have to be exposed to (that it is internally using an Array). On the other hand, IndexOutOfBoundsException directly relates to the Index (off or len parameters) being passed to the method.

  • Problem when calling a method

    hello,
    I have a problem when Im trying to call the make method that in the Tree class.
    Im calling it from the main method like you can see and It writes:
    -Cannot make a static reference to the non-static method make() from the type Tree.
    Can anyone help me please and tell me what is the problem?
    Im using Eclipse 3.1.2
    Thank you.
    //import java.lang.Object;
    //import java.lang.reflect.Array;
    //structure of the node
    class mainClass extends Tree {
         public static void main(String args[]){
              Tree.make();
              //char temporary[]=new char[9];
              //Tic_Tac_Toe pointersToNodes[]=new Tic_Tac_Toe[9];
              //for(j=0;j<9;j++)
                   //temporary[j]='b';     
    public class Tic_Tac_Toe {
         char currentCaseVector[]=new char[9];
         Tic_Tac_Toe PointersToNodes[]=new Tic_Tac_Toe[9];
         int evaluation;
    //class that builds the game tree
    class Tree {
         public Tic_Tac_Toe T1=new Tic_Tac_Toe();
         //char currentCaseVector[]=new char[9];
         public char currentSign;
         Tree(){
             resetCurrentCaseArray(T1);
             //T1.currentCaseVector.setSize(9);
              //System.out.println(T1.currentCaseVector.elementAt(2));
         void make(){
              Tic_Tac_Toe T = new Tic_Tac_Toe();
              int howMuchCloser,i;
              Tree tree=new Tree();
              for(i=0;i<9;i++)
                   T.currentCaseVector='b';
              howMuchCloser=1;
              for(i=0;i<9;i++){
                   T.PointersToNodes[findAvailablePlaceOnPointersToNodes(T)]=tree.buildNewTree(1,'o',T.currentCaseVector,howMuchCloser);
                   howMuchCloser++;
         Tic_Tac_Toe buildNewTree(int i,char currentSign,char temp[],int howMuchCloser)throws ArrayIndexOutOfBoundsException{
              int j=0;
              //int howMuchCloser=1;
              //for(j=i;j<9;j++){
              Tic_Tac_Toe T1=new Tic_Tac_Toe();
              currentSign=changeSign(currentSign);
              resetCurrentCaseArray(T1);
              //try{
              setBoard(T1.currentCaseVector,temp,howMuchCloser,currentSign);
              //catch(ArrayIndexOutOfBoundsException e){
                   //System.out.print("ArrayIndexOutOfBoundsException");
                   //System.out.println(i);          
              printTest(T1);
              temp=T1.currentCaseVector;
              howMuchCloser=1;
              if((isFull(T1.currentCaseVector))==true)
                   return T1;
              if(checkWin(T1)){
                   return T1;
              //printTest(T1);
                   //break;
              for(j=i;j<9;j++){
                   T1.PointersToNodes[findAvailablePlaceOnPointersToNodes(T1)]=buildNewTree(i+1,currentSign,temp,howMuchCloser);                              
                   howMuchCloser++;
                        //if(checkIfBlankEqualOne(T1.currentCaseVector)==false)
                   //howMuchCloser++;
                   //T1.PointersToNodes[findAvailablePlaceOnPointersToNodes(T1)]=buildNewTree(i+1,currentSign,temp);
         return T1;
         int findCloser(char charArray[],int howMuchCloser){
              int i;
              for(i=0;i<9;i++){
                   if (charArray[i]=='b'){
                        howMuchCloser--;
                   else
                        continue;
                   if (howMuchCloser==0)
                        break;     
              return i;
         void setBoard(char current[],char previous[],int howMuchCloser,char iksOrCircle){
                   int i;
                   for(i=0;i<9;i++){
                        current[i]=previous[i];/******/
                   current[findCloser(current,howMuchCloser)]=iksOrCircle;
         char changeSign(char sign){
              if(sign=='x')
                   return 'o';
              else
                   return 'x';
         boolean isFull(char array[]){
              int i;
              for(i=0;i<9;i++){
                   if(array[i]=='b'){
                        return false;
              return true;
         void resetCurrentCaseArray(Tic_Tac_Toe T1){
              for(int i=0;i<9;i++)
                   T1.currentCaseVector[i]='b';
         boolean checkWin(Tic_Tac_Toe T1){
              int count1=0;
              int count2=0;
              //checking columns
              int i,j;
              for(i=0;i<3;i++){
                   for(j=i;j<(i+7);j+=3){
                        if(T1.currentCaseVector[j]=='x')
                             count1++;
                        if(T1.currentCaseVector[j]=='o')
                             count2++;
                   if(count1==3)
                        return true;
                   if(count2==3)
                        return true;
                   count1=0;
                   count2=0;
              //checking rows
              for(i=0;i<7;i+=3){
                   for(j=i;j<(i+3);j++){
                        if(T1.currentCaseVector[j]=='x')
                             count1++;
                        if(T1.currentCaseVector[j]=='o')
                             count2++;
                   if(count1==3)
                        return true;
                   if(count2==3)
                        return true;
                   count1=0;
                   count2=0;
              //checking diagonal
              for(i=0;i<9;i+=4){
                   if(T1.currentCaseVector[i]=='x')
                        count1++;
                   if(T1.currentCaseVector[i]=='o')
                        count2++;
              if(count1==3)
                   return true;
              if(count2==3)
                   return true;
              count1=0;
              count2=0;
              for(i=2;i<7;i+=2){
                   if(T1.currentCaseVector[i]=='x')
                        count1++;
                   if(T1.currentCaseVector[i]=='o')
                        count2++;
              if(count1==3)
                   return true;
              if(count2==3)
                   return true;
              return false;
         public int findAvailablePlaceOnPointersToNodes(Tic_Tac_Toe tic_tac_toe){
              int i;
              for(i=0;i<9;i++)
                   if(tic_tac_toe.PointersToNodes[i]==null)
                        return i;
              return -1;
         void printTest(Tic_Tac_Toe T1){
              for(int i=0;i<9;i++)
                   System.out.println(T1.currentCaseVector[i]);
         boolean checkIfBlankEqualOne(char array[]){
              for(int i=0;i<9;i++){
                   if(i<8)
                        if(array[i]=='b')
                             return false;
              if(array[8]=='b')
                   return true;
              return false;
         /*void makeFirst(char temporary[]){
              for(int i=0;i<9;i++)
                   temporary[i]='b';

    I have two things in mind:
    1. either modify the make() in class Tree as static
    static void make() {//caution u may have to worry about instance variables referenced under this method2.
    under your main static method, invoke it like this instead
    mainClass mc=new mainClass();
    mc.make();//not Tree.make();

  • Exception in finally

    hi,
    i throw an Exception in try block and also throw an Exception in finally block. why do i get only the Exception thrown in finally block.
    i completely lose the Exception thrown in try block.
    The reason i'm asking this is because of the way JUnit is written.
    They call Setup and tests in try block and tearDown in a finally block.
    if an Exception happens in test and also Exception happens in tearDown, the test results show the test failed with exception in tearDown. Actually i expect the results to show as test failed in the test. Is this a java bug?
    thanks
    venkat

    If I did understand your question right, I find it very strange. For my it works as expected.
    Sounds very strange, you should get the thrown Exception in both the try-catch and in your finally-try-catch.
    try to just fill your stack and see if it will be displayd later in the finallys thrown exception. (use the fillinstacktrace).
        public void doSomething()
            int[] a = new int[2];
            String b = null;
            try
                System.out.println( a[3] );
            catch( ArrayIndexOutOfBoundsException aioobe )
                System.out.println("in catch");
                sleep(500);
                aioobe.printStackTrace();
                throw (ArrayIndexOutOfBoundsException) aioobe.fillInStackTrace();
            finally
                try
                    System.out.println( b.length() );
                catch( NullPointerException npe )
                    System.out.println("in finally");
                    sleep(500);
                    npe.printStackTrace();
        }good luck!

  • Exception on overridden methods

    hi ,
    we know that An overriding method in a subclass may only throw exceptions declared in the parent class or children of the exceptions declared in the parent class. but in a program it is written
    class base {
    public static void method1() {
    public class child extends base
    public static void method1() throws ArrayIndexOutOfBoundsException
    its being compiled ok.
    but when me writting
    class base {
    public static void method1() {
    public class child extends base
    public static void method1() throws Exception
    its giving compilation error.
    please explain this....

    hi ,
    we know that An overriding method in a subclass may
    only throw exceptions declared in the parent class or
    children of the exceptions declared in the parent
    class. but in a program it is written
    This only applies to checked exceptions. It does not apply to unchecked exceptions like ArrayIndexOutOfBounds. Methods that throw unchecked exceptions do not need to have a throws cause, although including a throws cause for an unchecked exception is allowed.
    If you change your code so the method throws a checked exception, you will get the error.
    http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html#67305

  • Exception occurred during event dispatching:java.lang.ArrayIndexOutOfBounds

    hi
    suppose i have 4 rows in my table
    i m trying to access first colunm in all rows with a for loop
    for(r0w=0;row<4;row++)
    getValueAt(row,0);
    its throwing ArrayIndexOutOfBoundsException for teh last row
    plz help me its urgent

    Are you sure there are four rows?
    What does getRowCount() return?

  • Path Finder in a 2D Grid Map With Different Terrain Types

         I have been thinking for a while on path finding game algoritms and I can up with one idea witch I want to publish. The goal of my project is when I have a 2 dimensional grid map where squares can have different movement cost, like in Civilization II, to find the shortest way from one point in the map to another. I've used the Breathed First Search Engine. If you are not familiar to this search engine it is better to read about it first because I am not fcusing on it and I assume that you now how it works. You can read about it at the book "Practical Artificial Intelligence Programming in Java" writen by Mark Watson, witch is freely distributed at www.markwatson.com.
         Actually the idea of this 2D grid path finder is to use a third dimension witch have a size equal to the highest movement cost among all terrain types. This helps solving the problem with the different movement cost of the squates. By adding this abstract third dimension it is posible to use the Breadth First Search Engine.
         I this example the movementcost of a terrain type is always the same, no matter from witch square to with are you going (like in Civilization II but I haven't included roads or railroads). For example if you want to go from one square A to another square B with movement cost X (A and B are attached) you must go "up stairs" in the third dimension X - 1 times and then move to square B. But when you step on square B you are again at the lowest floor. So if you want to come back to the previous square A and it have movement cost Y first you must go floor Y and then jump in square A. And now you are again at the lowest floor at square A. When you move from one square to another you go always at the lowest floor. This is the way I handle with different movement costs.
         When you find the path to the goal point it is in 3 dimensions. So you must just project it in the 2D map and that's all you have the shortest path.
         I am sure this is not the best way to code this search engine but this is just the first scratch with no optimisation and so on. If I make a 100x100 randomly generated map it takes on my configuration(400Mhz Pentium II CPU with ASUS P2B MotherBoard on 100 MHz and 256 MB SD RAM on 133 MHz but because of my MB on 100MHz) around 1000 miliseconds (1000 miliseconds = 1 second) to find the shortest path from (1, 1) to (100, 100) witch is pretty good compare to the goTo function in Civilization II witch does not finds the shortest path at all and have made hundrets of gamers angry. This is amazing that nowadays there are so many games with bad path finding.
         This project includes:
    1. The PathFinder class witch does the jub.
    2. The Map class witch has a generator for a random map in it.
    3. The class TerrainType, every square on the map is based on this class.
    4. The class TerrainTypes witch is the set of all terrain types used in the map.
    5. The class PathFinderTest witch just test the path finder.
    To test this project put all files in one directory and run PathFinderTest.java.
    Map.java:
    import java.util.Vector;
    import java.util.Random;
    //This class just creates a random map and keeps it. I will not comment on this.
    class Map {
      //here is kept the information about the terrain types placed in the map. Where
      //every terrain type has a specific movement cost.
      private int[][] terrain;
      public TerrainTypes terrainTypes;
      private int landMass;
      private int width;
      private int height;
      private int highestMovementCost;
      public Map(int aWidth, int aHeight) {
        width = aWidth;
        height = aHeight;
        terrainTypes = new TerrainTypes();
        highestMovementCost = terrainTypes.getHighestMovementCost();
        terrain = new int[width][height];
        landMass = 0;
        generateRandomMap();
      public void clearGoalAndStartLocFromWater(int sx, int sy, int gx, int gy) {
        terrain[gx][gy] = 0;
        terrain[sx][sy] = 0;
      private void expandWater() {
        int waterConstant = 40;
        int waterExpansion = 2;
        int[][] moreWater = new int[width][height];
        Random randomizer = new Random();
        for (int t = 0; waterExpansion > t; t++) {
          for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
              if (i + 1 >= 0 && j >= 0 && i + 1 < width && j < height) {
                if (terrain[i + 1][j] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i + 1][j] = 1;
              if (i + 1 >= 0 && j - 1 >= 0 && i + 1 < width && j - 1 < height) {
                if (terrain[i + 1][j - 1] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i + 1][j - 1] = 1;
              if (i >= 0 && j - 1 >= 0 && i < width && j - 1 < height) {
                if (terrain[i][j - 1] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i][j - 1] = 1;
              if (i - 1 >= 0 && j - 1 >= 0 && i - 1 < width && j - 1 < height) {
                if (terrain[i - 1][j - 1] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i - 1][j - 1] = 1;
              if (i - 1 >= 0 && j >= 0 && i - 1 < width && j < height) {
                if (terrain[i - 1][j] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i - 1][j] = 1;
              if (i - 1 >= 0 && j + 1 >= 0 && i - 1 < width && j + 1 < height) {
                if (terrain[i - 1][j + 1] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i - 1][j + 1] = 1;
              if (i >= 0 && j + 1 >= 0 && i < width && j + 1 < height) {
                if (terrain[i][j + 1] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i][j + 1] = 1;
              if (i + 1 >= 0 && j + 1 >= 0 && i + 1 < width && j + 1 < height) {
                if (terrain[i + 1][j + 1] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i + 1][j + 1] = 1;
        for (int i = 0; i < width; i++) {
          for (int j = 0; j < height; j++) {
            if (moreWater[i][j] == 1) {
              terrain[i][j] = 4;
      private void generateRandomMap() {
        Random randomizer = new Random();
        for (int i = 0; i < width; i++) {
          for (int j = 0; j < height; j++) {
            if (randomizer.nextInt(3) == 1)
              terrain[i][j] = 0;
            else if (randomizer.nextInt(2) == 1)
              terrain[i][j] = 1;
            else if (randomizer.nextInt(2) == 1)
              terrain[i][j] = 3;
            else if (randomizer.nextInt(2) == 1)
              terrain[i][j] = 2;
            else if (randomizer.nextInt(2) == 1)
              terrain[i][j] = 2;
            else if (randomizer.nextInt(2) == 1)
              terrain[i][j] = 1;
            else if (randomizer.nextInt(2) == 1)
              terrain[i][j] = 3;
            else
              terrain[i][j] = randomizer.nextInt(5);
        expandWater();
        for (int i = 0; i < width; i++) {
          for (int j = 0; j < height; j++) {
            if (terrain[i][j] != 0)
              landMass++;
      public int getMapHeight() {
        return height;
      public int getMapWidth() {
        return width;
      public int getSquareID(int x, int y) {
        return terrain[x][y];
      public int getSquareMovementCost(int x, int y) {
        return terrainTypes.getMovementCost(terrain[x][y]);
    }PathFinder.java:
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.Vector;
    public class PathFinder {
      private BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
      //The array t3D[][] represents the 2D square map where t3D.leght = map width
      //and t3D[x].lenght = map width (-1 < x < t3D.leght). The third dimension
      //is refered to the square's movement cost, witch is definite by terrain.
      //The fourth dimension will be with lenght = 3. When running the search engine
      //(expanding the explored squares) this 3 values will keep the position of
      //the previous square in 3 dimension, witch are width, height and the maximum
      //movement cost among all squares.
      private int[][][][] squares3DReference;
      //Keeps information witch squares are visited.
      private boolean[][][] visitedSquares;
      private Map map;
      //this is the queue used in the Breathed First Seatch.
      private Vector queue3D;
      //Here is saved the shortest path
      private Vector path2D;
      private int highestMovementCost;
      public PathFinder(Map aMap) {
        map = aMap;
        queue3D = new Vector();
        path2D = new Vector();
        squares3DReference = new int[map.getMapWidth()][map.getMapHeight()][][];
        visitedSquares = new boolean[map.getMapWidth()][map.getMapHeight()][];
        highestMovementCost = map.terrainTypes.getHighestMovementCost();
        buildAbstract3DTerrain();
      private void buildAbstract3DTerrain() {
        for (int x = 0; x < map.getMapWidth(); x++) {
          for (int y = 0; y <map.getMapHeight(); y++) {
            int movementCost = map.terrainTypes.getMovementCost(map.getSquareID(x, y));
            if ( movementCost > 0) {
              visitedSquares[x][y] = new boolean[highestMovementCost];
              squares3DReference[x][y] = new int[highestMovementCost][3];
              for (int z = 0; z < highestMovementCost; z++) {
                for (int t = 0; t < 3; t++) {
                  squares3DReference[x][y][z][t] = -1;
      private boolean isMoveValid(int x, int y, int z, int x2, int y2, int z2) {
        if ( x < 0 || y < 0 || z < 0 || x2 < 0 || y2 < 0 || z2 < 0 || x >= map.getMapWidth() || y >= map.getMapHeight() || z >= highestMovementCost ||  x2 >= map.getMapWidth() || y2 >= map.getMapHeight() || z2 >= highestMovementCost)
          return false;
        if (map.terrainTypes.getMovementCost(map.getSquareID(x2, y2)) < 1)
          return false;
        if (visitedSquares[x2][y2][z2])
          return false;
        if (x == x2 && y == y2)
          return true;
        else {
          if (z == map.terrainTypes.getMovementCost(map.getSquareID(x2, y2)) - 1)
            return true;
          else
            return false;
      private void clearPreviousSearchData() {
        queue3D.clear();
        path2D.clear();
        for (int x = 0; x < map.getMapWidth(); x++) {
          for (int y = 0; y < map.getMapHeight(); y++) {
            if (squares3DReference[x][y] != null) {
              for (int z = 0; z < highestMovementCost; z++) {
                visitedSquares[x][y][z] = false;
                for (int t = 0; t < 3; t++) {
                  squares3DReference[x][y][z][t] = -1;
      private Vector copyPath2D() {
        Vector path = new Vector();
        for (int i = 0; i < path2D.size(); i++) {
          path.add(path2D.get(i));
        return path;
      public Vector findPath(int sX, int sY, int gX, int gY) {
        int head = 0;
        int tail = 0;
        int x = sX;
        int y = sY;
        int z = 0;
        visitedSquares[x][y][z] = true;
        mainLoop: {
          while (tail <= head) {
            int[][] moves = getPosibleMoves(x, y, z);
            for (int i = 0; i < 9; i++) {
              if (moves[i] != null) {
                squares3DReference[moves[0]][moves[i][1]][moves[i][2]][0] = x;
    squares3DReference[moves[i][0]][moves[i][1]][moves[i][2]][1] = y;
    squares3DReference[moves[i][0]][moves[i][1]][moves[i][2]][2] = z;
    queue3D.add(moves[i]);
    if (moves[i][0] == gX && moves[i][1] == gY) {
    break mainLoop;
    visitedSquares[moves[i][0]][moves[i][1]][moves[i][2]] = true;
    head++;
    if (queue3D.size() == 0 || queue3D.size() == tail)
    break mainLoop;
    int[] nextInQueue = ((int[]) queue3D.get(tail));
    x = nextInQueue[0];
    y = nextInQueue[1];
    z = nextInQueue[2];
    tail++;
    if (squares3DReference[gX][gY][0][0] == -1) {
    clearPreviousSearchData();
    return path2D;
    fillpath2D(sX, sY, gX, gY);
    Vector path = copyPath2D();
    clearPreviousSearchData();
    return path;
    private int[][] getPosibleMoves(int x, int y, int z) {
    int[][] moves = new int[9][3];
    if (isMoveValid(x, y, z, x + 1, y, 0)) {
    moves[0][0] = x + 1;
    moves[0][1] = y;
    moves[0][2] = 0;
    else
    moves[0] = null;
    if (isMoveValid(x, y, z, x + 1, y - 1, 0)) {
    moves[1][0] = x + 1;
    moves[1][1] = y - 1;
    moves[1][2] = 0;
    else
    moves[1] = null;
    if (isMoveValid(x, y, z, x, y - 1, 0)) {
    moves[2][0] = x;
    moves[2][1] = y - 1;
    moves[2][2] = 0;
    else
    moves[2] = null;
    if (isMoveValid(x, y, z, x - 1, y - 1, 0)) {
    moves[3][0] = x - 1;
    moves[3][1] = y - 1;
    moves[3][2] = 0;
    else
    moves[3] = null;
    if (isMoveValid(x, y, z, x - 1, y, 0)) {
    moves[4][0] = x - 1;
    moves[4][1] = y;
    moves[4][2] = 0;
    else
    moves[4] = null;
    if (isMoveValid(x, y, z, x - 1, y + 1, 0)) {
    moves[5][0] = x - 1;
    moves[5][1] = y + 1;
    moves[5][2] = 0;
    else
    moves[5] = null;
    if (isMoveValid(x, y, z, x, y + 1, 0)) {
    moves[6][0] = x;
    moves[6][1] = y + 1;
    moves[6][2] = 0;
    else
    moves[6] = null;
    if (isMoveValid(x, y, z, x + 1, y + 1, 0)) {
    moves[7][0] = x + 1;
    moves[7][1] = y + 1;
    moves[7][2] = 0;
    else
    moves[7] = null;
    if (isMoveValid(x, y, z, x, y, z + 1)) {
    moves[8][0] = x;
    moves[8][1] = y;
    moves[8][2] = z + 1;
    else
    moves[8] = null;
    return moves;
    private void fillpath2D(int sX, int sY, int gX, int gY) {
    int[] gLoc = {gX, gY};
    path2D.add(gLoc);
    int x = gX;
    int y = gY;
    int z = 0;
    while (x != sX || y != sY) {
    int x2 = squares3DReference[x][y][z][0];
    int y2 = squares3DReference[x][y][z][1];
    int z2 = squares3DReference[x][y][z][2];
    x = x2;
    y = y2;
    z = z2;
    if (z == 0) {
    int[] loc = {x, y};
    path2D.insertElementAt(loc, 0);
    PathFinderTest.java
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.Vector;
    public class PathFinderTest {
      static BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
      static Map map;
      static int startX;
      static int startY;
      static int goalX;
      static int goalY;
      public static void main(String[] args) throws Exception {
        System.out.print("Enter map size.\nx = ");
        int width = Integer.parseInt(consoleReader.readLine());
        System.out.print("y = ");
        int height = Integer.parseInt(consoleReader.readLine());
        System.out.print("Enter strting location.\nx = ");
        startX = Integer.parseInt(consoleReader.readLine()) - 1;
        System.out.print("y = ");
        startY = Integer.parseInt(consoleReader.readLine()) - 1;
        System.out.print("Enter goal location.\nx = ");
        goalX = Integer.parseInt(consoleReader.readLine()) - 1;
        System.out.print("y = ");
        goalY = Integer.parseInt(consoleReader.readLine()) - 1;
        if (goalX < 0 || goalY < 0 || startX < 0 || startY < 0 || goalX >= width || goalY >= height || startX >= width || startY >= height) {
          System.out.println("Invalid parameters found. Program will exit");
          System.exit(0);
        map = new Map(width, height);
        map.clearGoalAndStartLocFromWater(startX, startY, goalX, goalY);
        printSolution(new Vector());
        PathFinder pathFinder = new PathFinder(map);
        long before = System.currentTimeMillis();
        Vector path = pathFinder.findPath(startX, startY, goalX, goalY);
        long after = System.currentTimeMillis();
        long time = after - before;
        printSolution(path);
        if (path.size() == 0)
          System.out.println("No path found.");
        else
          System.out.println("Path found.");
        System.out.println("Finding the path took " + time + " milliseconds");
      static void printSolution(Vector path) {
        boolean[][] pathOnMap = new boolean[map.getMapWidth()][map.getMapHeight()];
        for (int i = 0; path.size() > i; i++) {
          int[] move = (int[]) path.get(i);
          pathOnMap[move[0]][move[1]] = true;
        for (int y = 0; y < map.getMapHeight(); y++) {
          for (int x = 0; x < map.getMapWidth(); x++) {
            System.out.print(" ");
            if (pathOnMap[x][y] == false)
              System.out.print(" ");
            else
              System.out.print("0");
            if (x == startX && y == startY)
              System.out.print("S");
            else if (x == goalX && y == goalY)
              System.out.print("G");
            else
              System.out.print(map.terrainTypes.getNameFirstLetter(map.getSquareID(x, y)));
          System.out.println();
        System.out.println();
    }TerrainType.java:
    public class TerrainType {
      private int movementCost;
      private String name;
      TerrainType(int aMovementCost, String aName) {
        movementCost = aMovementCost;
        name = aName;
      public int getMovementCost() {
        return movementCost;
      public String getName() {
        return name;
      public String getNameFirstLetter() {
        return name.substring(0, 1).toUpperCase();
    }TerrainTypes.java:
    import java.util.Vector;
    public class TerrainTypes {
      //Here are saved the terrain types with the map has. ElementAt 'i' in
      //setOfTypes is represented by the number in Map.terrain[x][y] witch is
      //equal to i, were x, y are random integer as soon as they do not
      //throw ArrayIndexOutOfBoundsException. Actually this is a coding to know
      //a specific square in the map to witch terrain type is refered in setOfTypes.
      private Vector setOfTypes;
      public TerrainTypes() {
        setOfTypes = new Vector();
        setOfTypes.add(new TerrainType(1, "Plains"));
        setOfTypes.add(new TerrainType(2, "Forst"));
        setOfTypes.add(new TerrainType(3, "Jungle"));
        setOfTypes.add(new TerrainType(4, "Mountain"));
        setOfTypes.add(new TerrainType(-1, "X"));
      public int getMovementCost(int i) {
        return ((TerrainType) setOfTypes.get(i)).getMovementCost();
      public String getName(int i) {
        return ((TerrainType) setOfTypes.get(i)).getName();
      public String getNameFirstLetter(int i) {
        return ((TerrainType) setOfTypes.get(i)).getNameFirstLetter();
      public int getHighestMovementCost() {
        int max = 1;
        for (int i = 0; setOfTypes.size() > i; i++) {
          int movementCost = ((TerrainType) setOfTypes.get(i)).getMovementCost();
          if ( movementCost > 0) {
            if (max < movementCost)
              max = movementCost;
        return max;
    }I hope this program will be helpful.
    Sogartar

    Why is such a smart guy like you not using A*
    It is a general known algorithm which will find the
    optimal solution in a finite search-space (within a minimal time).
    The calculation time for the A* algorithm is influenced by two parameters:
    1 - cumulative cost
    2 - minimal expected additional cost
    The calculation of these two costs has a great influence on the
    solution.
    I think the actual problems most games experience with shortest path calculatoin are
    1 - very little time to spent calculating the shortest path
    The quickest solution might be the best for the game
    If your solution takes 1 second for the calculation of a path for one element on the board (100x100)
    What would it take for the game to calculate the path for all elements controlled by the computer ??
    If the computer controls two players which each have 50 elements to control, it would take forever...
    Don't even consider the usage of a larger board (200x200 would take 4 seconds/element when
    algorithm has complexity O(n))
    2 - low priority.
    Users tend to forgive a bad shortest path-algorithm most of the time,
    but not a bad display, bad pictures,...
    This is why most shortest-path algorithms within games were
    developed as a depth first search,
    within some earlier games this was even developed as
    a rule which went straight to the endlocation and
    takes a right/left turn when blocked by water/wall/...
    So the actual steps you should take are:
    1 - develop a normal breath-first search (to get going)
    2 - develop a normal depth-first search (to compare speed and solution with)
    3 - develop a normal dijkstra algorithm (sometimes called A)
    4 - develop a best first algorithm (called A*)
    5 - develop other AI-algorithms building upon A* (tabu-search, limited memory A*,...)
    6 - develop some other AI-algorithms (Genetic Algorithms, Simulated Annealing,...)
    7 - compare and tweak/change all search-algorithms for
    7 - a - size of maps (small versus huge)
    7 - b - optimality of the solution
    7 - c - actual usage for your game
    8 - !!! very important !!!
    Share the developed path algorithms along with remarks about speed, map-size,...
    with the rest of us. I would be very interested in such library.
    kind regards,

  • 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

  • PackedInteger encoding does not preserve order - but it could

    Currently, when viewed under the default unsigned lexical ordering, "packed" integers (and longs) do not sort numerically. This is because for values requiring two or more bytes, the "value" bytes are stored little endian.
    For example:
    <tt> 65910 -> 7a ff 00 01</tt>
    <tt> 65911 -> 7a 00 01 01</tt>
    However, it's possible to encode packed integers such that they still sort correctly. You can do this by modifying the existing PackedInteger algorithm as follows:
    <li>Invert the high-order bit on the first byte
    <li>Reverse the order of the second and subsequent bytes (if any)
    <li>If the original number was negative, invert (one's complement) the bits in the second and subsequent bytes (if any)
    Here's some examples showing the two encodings:
                  NUMBER             ENCODING         NEW ENCODING
    -9223372036854775808   8189ffffffffffff7f   018000000000000076
             -2147483648           8589ffff7f           0580000076
                  -65911             86000101             06fefeff
                  -65910             86ff0001             06feff00
                  -65655             86000001             06feffff
                  -65654               87ffff               070000
                  -65400               8701ff               0700fe
                  -65399               8700ff               0700ff
                    -375               870001               07feff
                    -374                 88ff                 0800
                    -120                 8801                 08fe
                    -119                   89                   09
                      -1                   ff                   7f
                       0                   00                   80
                       1                   01                   81
                     119                   77                   f7
                     120                 7801                 f801
                     374                 78ff                 f8ff
                     375               790001               f90100
                     631               790002               f90200
                   65399               7900ff               f9ff00
                   65400               7901ff               f9ff01
                   65654               79ffff               f9ffff
                   65655             7a000001             fa010000
                   65910             7aff0001             fa0100ff
                   65911             7a000101             fa010100
              2147483647           7b88ffff7f           fb7fffff88
    9223372036854775807   7f88ffffffffffff7f   ff7fffffffffffff88So the question is.. any particular reason this wasn't done? Would this alternate encoding be a useful addition? (I'm sure it's not possible to replace the current algorithm at this point).
    Thanks.

    greybird wrote:
    Thanks Archie. I appreciate this and I know you have good intentions. Unfortunately, we won't be able to incorporate any code from your svn repository. We can only incorporate submissions if the source code is posted here in our OTN forum.Not a problem... Here is the new class:
    package org.dellroad.sidekar.util;
    import com.sleepycat.bind.tuple.TupleInput;
    import com.sleepycat.bind.tuple.TupleOutput;
    import java.util.Arrays;
    * An improved version of Berkeley DB's {@link com.sleepycat.util.PackedInteger} class that packs values in such
    * a way that their order is preserved when compared using the default binary unsigned lexical ordering.
    * @see <a href="http://forums.oracle.com/forums/thread.jspa?messageID=4126254">Berkeley DB Java Edition forum posting</a>
    public final class PackedLong {
         * Maximum possible length of an encoded value.
        public static final int MAX_ENCODED_LENGTH = 9;
         * Minimum value for the first byte of a single byte encoded value. Lower values indicate a multiple byte encoded negative value.
        public static final int MIN_SINGLE_BYTE_ENCODED = 0x08;        // values 0x00 ... 0x07 prefix negative values
         * Maximum value for the first byte of a single byte encoded value. Higher values indicate a multiple byte encoded positive value.
        public static final int MAX_SINGLE_BYTE_ENCODED = 0xf7;        // values 0xf8 ... 0xff prefix positive values
         * Adjustment applied to single byte encoded values before encoding.
        public static final int ZERO_ADJUST = 127;                     // single byte value that represents zero
         * Minimum value that can be encoded as a single byte.
        public static final int MIN_SINGLE_BYTE_VALUE = MIN_SINGLE_BYTE_ENCODED - ZERO_ADJUST;          // -119
         * Maximum value that can be encoded as a singel byte.
        public static final int MAX_SINGLE_BYTE_VALUE = MAX_SINGLE_BYTE_ENCODED - ZERO_ADJUST;          // 120
         * Adjustment applied to multiple byte encoded negative values before encoding.
        public static final int NEGATIVE_ADJUST = -MIN_SINGLE_BYTE_VALUE;                               // 119
         * Adjustment applied to multiple byte encoded positive values before encoding.
        public static final int POSITIVE_ADJUST = -(MAX_SINGLE_BYTE_VALUE + 1);                         // -121
        // Cutoff values at which the encoded length changes (this field is package private for testing purposes)
        static final long[] CUTOFF_VALUES = new long[] {
            0xff00000000000000L - NEGATIVE_ADJUST,      // [ 0] requires 8 bytes
            0xffff000000000000L - NEGATIVE_ADJUST,      // [ 1] requires 7 bytes
            0xffffff0000000000L - NEGATIVE_ADJUST,      // [ 2] requires 6 bytes
            0xffffffff00000000L - NEGATIVE_ADJUST,      // [ 3] requires 5 bytes
            0xffffffffff000000L - NEGATIVE_ADJUST,      // [ 4] requires 4 bytes
            0xffffffffffff0000L - NEGATIVE_ADJUST,      // [ 5] requires 3 bytes
            0xffffffffffffff00L - NEGATIVE_ADJUST,      // [ 6] requires 2 bytes
            MIN_SINGLE_BYTE_VALUE,                      // [ 7] requires 1 byte
            MAX_SINGLE_BYTE_VALUE + 1,                  // [ 8] requires 2 bytes
            0x0000000000000100L - POSITIVE_ADJUST,      // [ 9] requires 3 bytes
            0x0000000000010000L - POSITIVE_ADJUST,      // [10] requires 4 bytes
            0x0000000001000000L - POSITIVE_ADJUST,      // [11] requires 5 bytes
            0x0000000100000000L - POSITIVE_ADJUST,      // [12] requires 6 bytes
            0x0000010000000000L - POSITIVE_ADJUST,      // [13] requires 7 bytes
            0x0001000000000000L - POSITIVE_ADJUST,      // [14] requires 8 bytes
            0x0100000000000000L - POSITIVE_ADJUST,      // [15] requires 9 bytes
        private PackedLong() {
         * Write the encoded value to the output.
         * @param output destination for the encoded value
         * @param value value to encode
        public static void write(TupleOutput output, long value) {
            output.makeSpace(MAX_ENCODED_LENGTH);
            int len = encode(value, output.getBufferBytes(), output.getBufferLength());
            output.addSize(len);
         * Read and decode a value from the input.
         * @param input input holding an encoded value
         * @return the decoded value
        public static long read(TupleInput input) {
            long value = decode(input.getBufferBytes(), input.getBufferOffset());
            input.skipFast(getReadLength(input));
            return value;
         * Determine the length (in bytes) of an encoded value without advancing the input.
         * @param input input holding an encoded value
         * @return the length of the encoded value
        public static int getReadLength(TupleInput input) {
            return getReadLength(input.getBufferBytes(), input.getBufferOffset());
         * Determine the length (in bytes) of an encoded value.
         * @param buf buffer containing encoded value
         * @param off starting offset of encoded value
         * @return the length of the encoded value
         * @throws ArrayIndexOutOfBoundsException if {@code off} is not a valid offset in {@code buf}
        public static int getReadLength(byte[] buf, int off) {
            int prefix = buf[off] & 0xff;
            if (prefix < MIN_SINGLE_BYTE_ENCODED)
                return 1 + MIN_SINGLE_BYTE_ENCODED - prefix;
            if (prefix > MAX_SINGLE_BYTE_ENCODED)
                return 1 + prefix - MAX_SINGLE_BYTE_ENCODED;
            return 1;
         * Determine the length (in bytes) of the encoded value.
         * @return the length of the encoded value, a value between one and {@link #MAX_ENCODED_LENGTH}
        public static int getWriteLength(long value) {
            int index = Arrays.binarySearch(CUTOFF_VALUES, value);
            if (index < 0)
                index = ~index - 1;
            return index < 8 ? 8 - index : index - 6;
         * Encode the given value into a new buffer.
         * @param value value to encode
         * @return byte array containing the encoded value
        public static byte[] encode(long value) {
            byte[] buf = new byte[MAX_ENCODED_LENGTH];
            int len = encode(value, buf, 0);
            if (len != MAX_ENCODED_LENGTH) {
                byte[] newbuf = new byte[len];
                System.arraycopy(buf, 0, newbuf, 0, len);
                buf = newbuf;
            return buf;
         * Encode the given value and write the encoded bytes into the given buffer.
         * @param value value to encode
         * @param buf output buffer
         * @param off starting offset into output buffer
         * @return the number of encoded bytes written
         * @throws ArrayIndexOutOfBoundsException if {@code off} is negative or the encoded value exceeds the given buffer
        public static int encode(long value, byte[] buf, int off) {
            int len = 1;
            if (value < MIN_SINGLE_BYTE_VALUE) {
                value += NEGATIVE_ADJUST;
                long mask = 0x00ffffffffffffffL;
                for (int shift = 56; shift != 0; shift -= 8) {
                    if ((value | mask) != ~0L)
                        buf[off + len++] = (byte)(value >> shift);
                    mask >>= 8;
                buf[off] = (byte)(MIN_SINGLE_BYTE_ENCODED - len);
            } else if (value > MAX_SINGLE_BYTE_VALUE) {
                value += POSITIVE_ADJUST;
                long mask = 0xff00000000000000L;
                for (int shift = 56; shift != 0; shift -= 8) {
                    if ((value & mask) != 0L)
                        buf[off + len++] = (byte)(value >> shift);
                    mask >>= 8;
                buf[off] = (byte)(MAX_SINGLE_BYTE_ENCODED + len);
            } else {
                buf[off] = (byte)(value + ZERO_ADJUST);
                return 1;
            buf[off + len++] = (byte)value;
            return len;
         * Decode a value from the given buffer.
         * @param buf buffer containing an encoded value
         * @param off starting offset of the encoded value in {@code buf}
         * @return the decoded value
         * @throws ArrayIndexOutOfBoundsException if {@code off} is negative or the encoded value is truncated
         * @see #getReadLength
        public static long decode(byte[] buf, int off) {
            int first = buf[off++] & 0xff;
            if (first < MIN_SINGLE_BYTE_ENCODED) {
                long value = ~0L;
                while (first++ < MIN_SINGLE_BYTE_ENCODED)
                    value = (value << 8) | (buf[off++] & 0xff);
                return value - NEGATIVE_ADJUST;
            if (first > MAX_SINGLE_BYTE_ENCODED) {
                long value = 0L;
                while (first-- > MAX_SINGLE_BYTE_ENCODED)
                    value = (value << 8) | (buf[off++] & 0xff);
                return value - POSITIVE_ADJUST;
            return (byte)(first - ZERO_ADJUST);
    }and here is the unit test:
    package org.dellroad.sidekar.util;
    import com.sleepycat.bind.tuple.TupleInput;
    import com.sleepycat.bind.tuple.TupleOutput;
    import com.sleepycat.je.DatabaseEntry;
    import org.dellroad.sidekar.TestSupport;
    import org.testng.annotations.DataProvider;
    import org.testng.annotations.Test;
    import static org.testng.Assert.assertEquals;
    public class PackedLongTest extends TestSupport {
        @Test(dataProvider = "encodings")
        public void testEncoding(long value, String string) {
            // Test direct encoding
            byte[] expected = ByteArrayEncoder.decode(string);
            byte[] actual = PackedLong.encode(value);
            assertEquals(actual, expected);
            // Test write()
            TupleOutput out = new TupleOutput();
            PackedLong.write(out, value);
            assertEquals(out.toByteArray(), expected);
            // Test getWriteLength()
            assertEquals(actual.length, PackedLong.getWriteLength(value));
            // Test decoding
            long value2 = PackedLong.decode(actual, 0);
            assertEquals(value2, value);
            // Test read()
            TupleInput input = JEUtil.toTupleInput(new DatabaseEntry(actual));
            assertEquals(actual.length, PackedLong.getReadLength(input));
            value2 = PackedLong.read(input);
            assertEquals(value2, value);
            // Test getReadLength()
            assertEquals(actual.length, PackedLong.getReadLength(actual, 0));
        @Test(dataProvider = "lengths")
        public void testEncodedLength(long value, int expected) {
            int actual = PackedLong.getWriteLength(value);
            assertEquals(actual, expected);
            byte[] buf = PackedLong.encode(value);
            assertEquals(buf.length, expected);
        @DataProvider(name = "encodings")
        public Object[][] genEncodings() {
            return new Object[][] {
                // Corner cases
                { 0x8000000000000000L, "008000000000000077" },
                { 0xfeffffffffffff88L, "00feffffffffffffff" },
                { 0xfeffffffffffff89L, "0100000000000000" },
                { 0xfeffffffffffffffL, "0100000000000076" },
                { 0xfffeffffffffff88L, "01feffffffffffff" },
                { 0xfffeffffffffff89L, "02000000000000" },
                { 0xfffeffffffffffffL, "02000000000076" },
                { 0xfffffeffffffff88L, "02feffffffffff" },
                { 0xfffffeffffffff89L, "030000000000" },
                { 0xfffffeffffffffffL, "030000000076" },
                { 0xfffffffeffffff88L, "03feffffffff" },
                { 0xfffffffeffffff89L, "0400000000" },
                { 0xfffffffeffffffffL, "0400000076" },
                { 0xfffffffffeffff88L, "04feffffff" },
                { 0xfffffffffeffff89L, "05000000" },
                { 0xfffffffffeffffffL, "05000076" },
                { 0xfffffffffffeff88L, "05feffff" },
                { 0xfffffffffffeff89L, "060000" },
                { 0xfffffffffffeffffL, "060076" },
                { 0xfffffffffffffe88L, "06feff" },
                { 0xfffffffffffffe89L, "0700" },
                { 0xfffffffffffffeffL, "0776" },
                { 0xffffffffffffff88L, "07ff" },
                { 0xffffffffffffff89L, "08" },
                { 0xffffffffffffffa9L, "28" },
                { 0xffffffffffffffc9L, "48" },
                { 0xffffffffffffffe9L, "68" },
                { 0xffffffffffffffffL, "7e" },
                { 0x0000000000000000L, "7f" },
                { 0x0000000000000001L, "80" },
                { 0x0000000000000071L, "f0" },
                { 0x0000000000000077L, "f6" },
                { 0x0000000000000078L, "f7" },
                { 0x0000000000000079L, "f800" },
                { 0x0000000000000178L, "f8ff" },
                { 0x0000000000000179L, "f90100" },
                { 0x0000000000010078L, "f9ffff" },
                { 0x0000000000010079L, "fa010000" },
                { 0x0000000001000078L, "faffffff" },
                { 0x0000000001000079L, "fb01000000" },
                { 0x0000000100000078L, "fbffffffff" },
                { 0x0000000100000079L, "fc0100000000" },
                { 0x0000010000000078L, "fcffffffffff" },
                { 0x0000010000000079L, "fd010000000000" },
                { 0x0001000000000078L, "fdffffffffffff" },
                { 0x0001000000000079L, "fe01000000000000" },
                { 0x0100000000000078L, "feffffffffffffff" },
                { 0x0100000000000079L, "ff0100000000000000" },
                { 0x7fffffffffffff79L, "ff7fffffffffffff00" },
                { 0x7fffffffffffffffL, "ff7fffffffffffff86" },
                // Other cases
                { 0xffffffff80000000L, "0480000077" },
                { 0xfffffffffffefe89L, "05feff00" },
                { 0xfffffffffffefe8aL, "05feff01" },
                { 0xfffffffffffeff86L, "05fefffd" },
                { 0xfffffffffffeff87L, "05fefffe" },
                { 0xfffffffffffeff88L, "05feffff" },
                { 0xfffffffffffeff89L, "060000" },
                { 0xfffffffffffeff8aL, "060001" },
                { 0xffffffffffff0086L, "0600fd" },
                { 0xffffffffffff0087L, "0600fe" },
                { 0xffffffffffff0088L, "0600ff" },
                { 0xffffffffffff0089L, "060100" },
                { 0xfffffffffffffe86L, "06fefd" },
                { 0xfffffffffffffe87L, "06fefe" },
                { 0xfffffffffffffe89L, "0700" },
                { 0xfffffffffffffe8aL, "0701" },
                { 0xffffffffffffff87L, "07fe" },
                { 0xffffffffffffff88L, "07ff" },
                { 0xffffffffffffff89L, "08" },
                { 0xffffffffffffffffL, "7e" },
                { 0x0000000000000000L, "7f" },
                { 0x0000000000000001L, "80" },
                { 0x0000000000000077L, "f6" },
                { 0x0000000000000078L, "f7" },
                { 0x0000000000000176L, "f8fd" },
                { 0x0000000000000177L, "f8fe" },
                { 0x0000000000000178L, "f8ff" },
                { 0x0000000000000277L, "f901fe" },
                { 0x000000000000ff77L, "f9fefe" },
                { 0x000000000000ff78L, "f9feff" },
                { 0x000000000000ff79L, "f9ff00" },
                { 0x000000000000ff7aL, "f9ff01" },
                { 0x0000000000010076L, "f9fffd" },
                { 0x0000000000010077L, "f9fffe" },
                { 0x0000000000010078L, "f9ffff" },
                { 0x0000000000010079L, "fa010000" },
                { 0x000000000001007aL, "fa010001" },
                { 0x0000000000010176L, "fa0100fd" },
                { 0x0000000000010177L, "fa0100fe" },
                { 0x000000007fffffffL, "fb7fffff86" },
                { 0x7fffffffffffffffL, "ff7fffffffffffff86" },
        @DataProvider(name = "lengths")
        public Object[][] genLengths() {
            return new Object[][] {
                // Check cutoff values
                {   PackedLong.CUTOFF_VALUES[ 0] - 1,      9   },
                {   PackedLong.CUTOFF_VALUES[ 0],          8   },
                {   PackedLong.CUTOFF_VALUES[ 1] - 1,      8   },
                {   PackedLong.CUTOFF_VALUES[ 1],          7   },
                {   PackedLong.CUTOFF_VALUES[ 2] - 1,      7   },
                {   PackedLong.CUTOFF_VALUES[ 2],          6   },
                {   PackedLong.CUTOFF_VALUES[ 3] - 1,      6   },
                {   PackedLong.CUTOFF_VALUES[ 3],          5   },
                {   PackedLong.CUTOFF_VALUES[ 4] - 1,      5   },
                {   PackedLong.CUTOFF_VALUES[ 4],          4   },
                {   PackedLong.CUTOFF_VALUES[ 5] - 1,      4   },
                {   PackedLong.CUTOFF_VALUES[ 5],          3   },
                {   PackedLong.CUTOFF_VALUES[ 6] - 1,      3   },
                {   PackedLong.CUTOFF_VALUES[ 6],          2   },
                {   PackedLong.CUTOFF_VALUES[ 7] - 1,      2   },
                {   PackedLong.CUTOFF_VALUES[ 7],          1   },
                {   PackedLong.CUTOFF_VALUES[ 8] - 1,      1   },
                {   PackedLong.CUTOFF_VALUES[ 8],          2   },
                {   PackedLong.CUTOFF_VALUES[ 9] - 1,      2   },
                {   PackedLong.CUTOFF_VALUES[ 9],          3   },
                {   PackedLong.CUTOFF_VALUES[10] - 1,      3   },
                {   PackedLong.CUTOFF_VALUES[10],          4   },
                {   PackedLong.CUTOFF_VALUES[11] - 1,      4   },
                {   PackedLong.CUTOFF_VALUES[11],          5   },
                {   PackedLong.CUTOFF_VALUES[12] - 1,      5   },
                {   PackedLong.CUTOFF_VALUES[12],          6   },
                {   PackedLong.CUTOFF_VALUES[13] - 1,      6   },
                {   PackedLong.CUTOFF_VALUES[13],          7   },
                {   PackedLong.CUTOFF_VALUES[14] - 1,      7   },
                {   PackedLong.CUTOFF_VALUES[14],          8   },
                {   PackedLong.CUTOFF_VALUES[15] - 1,      8   },
                {   PackedLong.CUTOFF_VALUES[15],          9   },
                // Check some other values
                { Long.MIN_VALUE,                               9   },
                { Long.MAX_VALUE,                               9   },
                { (long)Integer.MIN_VALUE,                      5   },
                { (long)Integer.MAX_VALUE,                      5   },
                { (long)Short.MIN_VALUE,                        3   },
                { (long)Short.MAX_VALUE,                        3   },
                { (long)Byte.MIN_VALUE,                         2   },
                { (long)Byte.MAX_VALUE,                         2   },
                { 0,                                            1   },
    }Edited by: archie172 on Mar 3, 2010 12:40 PM
    Removed copyright message.

  • JBO Exceptions

    Hi there,
    I'm fairly new to JDeveloper, and the Oracle Business Components, but after much playing around I've got them working nicely. We're using them inside a servlet, and we don't want the user names and passwords hardcoded into the app. Not a problem, we can just substitute variables into the Transaction.connect(String URL) method call. This all works great, unless you specify an incorrect username and password, in which case an unadvertised oracle.jbo.DMLException is thrown.
    My concern is that I was under the impression that Exceptions must be declared as 'thrown' by the method signature in order for the class to even compile. Given that this clearly isn't the case, what other undocumented Exceptions could be thrown by the Business Components that we don't find until we go live? Is there somewhere I can find out? And why did Oracle decide not to include these in the 'throws' clause of the method signature?
    Regards,
    Steve.
    null

    More Info from our Developers...
    Java supports two different kinds of exceptions:
    static exceptions and runtime exceptions.
    Static exceptions must be declared on the method declaration. As you
    know, code calling a method with static exceptions must either catch
    the exceptions or declare itself to throw the same or superclass exceptions.
    With runtime exceptions, they don't have to be declared on the method.
    Most 'famous' of these runtime exceptions are
    NullPointerException, ArrayIndexOutOfBoundsException,
    ClassCastException.
    Static exceptions, as the phrase suggests, are good for methods whose
    call chains are relatively static. If A calls B, and B calls C, and
    if this chain of calls does not change in arbitrary manner, exceptions thrown by C can be statically declared, forcing B to
    either handle or pass the exceptions.
    As you mentioned, what's nice about static exceptions is that it
    allows compile-time checking.
    Static exceptions are not necessarily appropriate all the time. If
    static exceptions were always appropriate, Java would not have
    bothered with runtime exceptions. If you think about
    NullPointerException, you will see why it wouldn't make sense to make
    it a static exception. NullPointerException can be thrown by any
    piece of Java code. If NullPointerException were a static exception,
    all methods would have to either (1) have catch block almost
    everywhere to handle NullPointerException, or (2) declare to throw NullPointerException.
    The reason why NullPointerException wouldn't make a good static
    exception is because it is ubiquitous. It can be thrown at unexpected places.
    Another reason for not making an exception static would be if code
    can easily be inserted in an overriding method (of a subclass) and
    cause that exception to be thrown. Let's take an example.
    Suppose
    ArrayOutOfIndexException were a static exception.
    Suppose I have the following method in the base class:
    public class BaseClass
    void myMethod()
    System.out.println("hello");
    Now, suppose I build a subclass on BaseClass and override
    myMethod,
    as in:
    public class SubClass extends BaseClass
    void myMethod()
    Further, I have some code in the body of SubClass.myMethod that deals
    with an array object, say
    void myMethod()
    int iArr = new int[2];
    // This line will throw ArrayIndexOutOfBoundsException
    iArr[3] = 0;
    If ArrayIndexOutOfBoundsException were static, all of a sudden,
    SubClass.myMethod would have to declare that it throws ArrayIndexOutOfBoundsException. However, since the base
    implementation myMethod did not mention any exception on its
    declaration, we can't put "throws
    ArrayIndexOutOfBoundsException" in
    the subclass implementation (Java doesn't allow this). The only
    thing SubClass.myMethod can do is either (1) catch ArrayIndexOutOfBoundsException and eat it or (2) wrap it in
    a runtime
    exception and throw the runtime exception.
    =====
    The main reason why we (BC4J) decided to use runtime exceptions
    and not static exceptions is for the two reasons that I described
    above: ubiquitous-ness of some exceptions and
    overriddability of methods.
    One of the big benefits of BC4J is tier-independent programming where
    the same piece of code can run in local mode or 3 tier (networked)
    mode. When running in 3 tier, any method can make a trip to middle
    tier server. This means (among other things) network failure or
    server failure can occur practically anywhere. If these exceptions
    were static, most BC4J methods would have to declare them on their methods.
    Also, BC4J has 'deferred' mode where data changes can be deferred
    and batched up on the client before they are sent to middle tier.
    Thus, method calls like setAttribute() can be batched and later sent
    to middle tier when something like createViewObject() is called. If
    BC4J exceptions were static, all possible exceptions that can be
    thrown by setAttribute, e.g., ValidationException, can be thrown by
    createViewObject because the setAttribute call was deferred. This
    will not only confuse the user (why should caller of createViewObject
    worry about validation failure?), but it will cause ubiquitous and
    often unnecessary declaring and handling of exceptions.
    Let's talk about the overriddability issue. One of BC4J's big
    benefits is customizability. The user can add their custom code and
    subclass and override methods at practically anywhere in the system.
    This makes management of exceptions quite cumbersome if they were
    static. For example, at first it may seem obvious that getAttribute() should never throw ValidationException, since
    it is unlikely getAttribute will change data.
    However, it is quite reasonable for getAttribute() to call
    setAttribute() for other calculated-but-cached-transiently data. For
    this situation, this overridden getAttribute now needs to throw
    ValidationException.
    This kind of arbitrary call chaining and customization means that we
    end up making most methods throw the most base class BC4J exception,
    namely JboException. To have all our methods declared to throw
    JboException would be meaningless, in much the same way as it would
    be meaningless for methods to be declared with 'throws Exception'.
    =====
    The official and best way to find out which exceptions that a method
    is known to throw would be the method's Java-doc. It's true that
    the list at the moment may not be complete at the moment, but Java-doc
    is the best place to start.
    Also, when you get an exception, take a look at the Java-doc for the
    exception class itself to figure out why it's thrown.
    I Hope this helps.
    John- JDeveloper Team
    null

Maybe you are looking for