Extending an Array

I have created a class of objects, with fields, constructors, methods, etc. So far, so good.
Now I would like to create an array of these objects, and I have some methods that I would like to create that would manipulate the objects in an array. Is it possible to create a class that extends array, and that is always an array of my object? (I'm not even sure how to ask my question properly)
Here's an example - given:
public class MyItem {
private String name;
private String description;
private String material;
public String getDescription() {
return description;
... (constructors & other methods omitted)
}// end of MyItem
I woudl like to create somethign like this
public class ArrayOfItem extends java.lang.Array {
public String getDescription (String theName) {
<code to find the MyItem in the array where MyItem.name = theName>
return MyItem.getDescription();
The thing is that this is dependent upon the array always containing MyItems; is this possible? Where could I find some examples of this? Or, am I better off just writing the methods I need into the program, rather than trying to create a new class?
Edited by: lkb3 on Feb 7, 2011 7:33 AM

Its more likely you want to extends ArrayList like
// works but not a good idea.
public class ArrayOfItem extends ArrayList<MyItem> {
}You are much better off wrapping the collection
// works but not very efficient.
public class ArrayOfItem extends  {
    final List<MyItem> myItems = new ArrayList<MyItem>();
}Assuming you have to lookup by name often you can wrap a Map instead.
public class ArrayOfItem extends  {
    final Map<String, MyItem> myItems = new LinekdHashMap<String, MyItem>();
    public void add(MyItem mi) [
        myItems.put(mi.getName(), mi);
    public String getDescription (String theName) {
        return myItems.get(theName).getDescription();
}Edited by: Peter Lawrey on Feb 7, 2011 3:57 PM

Similar Messages

  • How to extend an array?

    Hi,
    how to extend an array
    int[] b = new int[] {1, 2, 3};by adding 4, 5, 6 without copying?
    thanks a lot
    aldo

    You can't
         int [] b = {1,2,3};
         int [] a = {4,5,6};
         int [] tmp = new int [b.length + a.length];
         System.arraycopy(b, 0, tmp, 0, b.length);
         System.arraycopy(a, 0, tmp, b.length ,a.length);
         b = tmp;
         System.out.println(Arrays.toString(b));

  • Extending an array multiple times - Help!

    Hi everyone,
    I am very new to Java (doing my first class now) and I need some help with making an array larger. I have written a program that will display a list of products created in a static array. The program needs to include an "add" button, that will prompt for new product information, and add it to the array.
    I've managed to get this coded up to a point where my add button works (albeit only is adding product name at this point...will add the rest later once this works). The problem is, when I attempt to run the add button a second time, it does not grow out the length of the array. The result is that it updates the last record within the array with the new product information, rather than appending a new one. Here is the code I think is relevant (as I don't think you are allowed to entirely post school work):
    // Assignment: Inventory Program Part 6
    // Author:  Ryan MacDonald
    // Class uses both swing and awt components, also using number format for currency, and AWT events
    import javax.swing.*;
    import java.awt.*;
    import java.text.NumberFormat;
    import java.awt.event.*;
    // InventoryPart4 class
    public class InventoryPart6
         // Declare array of products
         static Product_Extender Item[] = new Product_Extender[4];
         // snip
         // snip
         // Main method
         public static void main ( String args[] )
              // Create a new product object
              Item[0] = new Product_Extender( 1, "Pink Markers", "Pentel", 31, 0.61 );
              Item[1] = new Product_Extender( 2, "Blue Pens", "Bic", 57, 0.30 );
              Item[2] = new Product_Extender( 3, "Red Markers", "Zebra", 62, 0.55 );
              Item[3] = new Product_Extender( 4, "Black Pens", "Bic", 73, 0.33 );
         // snip
         // snip
              // Make add button work
                   addAddButton.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                        Product_Extender newItem[] = new Product_Extender[Item.length + 1];
                        System.arraycopy(Item, 0, newItem, 0, Item.length);
                        newItem[newItem.length - 1] = new Product_Extender( newItem.length, productNameText.getText(), "Test New Item", 99, 0.99 );
                        Product_Extender Item[] = new Product_Extender[newItem.length];
                        System.arraycopy(newItem, 0, Item, 0, newItem.length);
                        // Update main text area with our new product information
                        mainText.setBorder(BorderFactory.createTitledBorder("Product Inventory (All Items)"));     // Create a title around the textarea with some text
                        mainText.setText( String.format("Product #" + "\t" + "Name" + "\t" + "Manufacturer" + "\t" + "Quantity" + "\t" + "Price" + "\t" + "Value" + "\t" + "Restocking Fee" + "\n") ); // Create a line of text with the product header information
                        // Loop through each item in the product array and append the information to the main text area for the product number, product name, quantity in stock, price per unit, total value of inventory, and restocking fee for this item
                        for(int i = 0; i < Item.length; i++) {
                        mainText.append(String.format(Item.getProductNumber() + "\t" + Item[i].getProductName() + "\t" + Item[i].getProductManufacturer() + "\t" + Item[i].getProductQuantity() + "\t" + NumberFormat.getCurrencyInstance().format(Item[i].getProductPrice()) + "\t" + NumberFormat.getCurrencyInstance().format(Item[i].getInventoryValue()) + "\t" + NumberFormat.getCurrencyInstance().format(Item[i].getRestockingFee()) + "\n" ) );
                        // Set array location
                        currentLoc = -1;
                        // Close window
                        addFrame.dispose();
         // snip
         // snip
         } // End method main
    } // End class InventoryPart6
    Basically here is my train of thought (although my logic could be ENTIRELY off, I'm very new here...).  From what I've read, there is no way to actually grow/extend an array.  The only option is to create a new one and populate it with the same data.
    1.  Since I can't grow it, I make a new array called "newItem" with Item.lengh + 1 as it's size
    2.  I then copy the contents of Item over to newItem
    3.  Since I need Item later, I recreate it with a new size of newItem.length
    4.  Copy the data from newItem over to Item
    5.  Print out the data from Item back to the main text area
    What I would like to do is rinse and repeat this process as many times as the user would like.  However as I said, it doesn't seem to work.  Each time it reiterates again, it sets Item.length back to 4, not having it grow each time (deduced this by adding a bunch of prints of variables to my window).
    Any help would be appreciated!!!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    nvrmore100 wrote:
    I actually have a lot of other buttons that manipulate the displaying of the array in various ways. I thought about creating a much larger array, but this would break all the functionality I have for displaying next, previous, last, items in the array.Then your functionality is incorrect. You should have a variable that keeps track of how many items are stored in the array. This will always allow you to access the last element. And when this variable reaches the size of the array only then do you increase the size of the array.
    I agree, I think this is exactly my issue, unfortunately I do not know where to go from here. Is there a way for me to recreate the Item array entirely, rather than having a local array to the addbutton action method?I already showed you how to fix your problem. Delete your line of code and replace it with mine.

  • How to Extend an Array of an Array of an Object

    Hi!
    I'm created these types in my DB:
    TYPE SONO_ROW AS OBJECT (DATO NUMBER, FECHA DATE);
    TYPE SONO_TABLE IS VARRAY(1000) OF SONO_ROW;
    TYPE SONO_ARRAY IS VARRAY(1000) OF SONO_TABLE;
    Well, I have a problem when I trying to load SONO_ARRAY, because I can't do a EXTEND for this Type:
    DECLARE
    V_MULTIVARRAY SONO_ARRAY;
    BEGIN
    -- Initialize the collection
    V_MULTIVARRAY := SONO_ARRAY(SONO_TABLE(SONO_ROW(77, SYSDATE)));
    -- Extend the collection
    V_MULTIVARRAY.EXTEND(10,1);
    V_MULTIVARRAY(2)(1) := SONO_ROW(1, SYSDATE);
    END;
    Whell, this code extend in 10 the element 1(SONO_TABLE), it is ok, but I don't know how to extend SONO_REG in order to insert elements for SONO_ROW: V_MULTIVARRAY(1)(2). I tried to do it of all the ways but without results.
    Someone could help me, please?
    Thanks,
    Fernando.

    Does this help?
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
    With the Partitioning, OLAP and Data Mining options
    SQL> DECLARE
      2     l_sono_array sono_array := sono_array ();
      3  BEGIN
      4     FOR i IN 1 ..10 LOOP
      5        l_sono_array.EXTEND;
      6        l_sono_array (i) := sono_table ();
      7       
      8        FOR j IN 1 .. 5 LOOP
      9           l_sono_array (i).EXTEND;
    10           l_sono_array (i) (j) := sono_row (j, SYSDATE);
    11        END LOOP;
    12       
    13     END LOOP;
    14  END;
    15  /
    PL/SQL procedure successfully completed.
    SQL>

  • Extend a Array of a Array of a Object

    Hi!
    I'm created these types in my DB:
    TYPE SONO_ROW AS OBJECT (DATO NUMBER, FECHA DATE);
    TYPE SONO_TABLE IS VARRAY(1000) OF SONO_ROW;
    TYPE SONO_ARRAY IS VARRAY(1000) OF SONO_TABLE;
    Well, I have a problem when I trying to load SONO_ARRAY, because I can't do a EXTEND for this Type:
    DECLARE
    V_MULTIVARRAY SONO_ARRAY;
    BEGIN
    -- Initialize the collection
    V_MULTIVARRAY := SONO_ARRAY(SONO_TABLE(SONO_ROW(77, SYSDATE)));
    -- Extend the collection
    V_MULTIVARRAY.EXTEND(10,1);
    V_MULTIVARRAY(2)(1) := SONO_ROW(1, SYSDATE);
    END;
    Whell, this code extend in 10 the element 1(SONO_TABLE), it is ok, but I don't know how to extend SONO_REG in order to insert elements for SONO_ROW: V_MULTIVARRAY(1)(2). I tried to do it of all the ways but without results.
    Someone could help me, please?
    Thanks,
    Fernando.

    Hi,
    possibly the article http://htmldb.oracle.com/pls/otn/f?p=2853:4:9828983748613764845::NO::P4_QA_ID:4322 will help you
    e.g.
    DECLARE
    V_MULTIVARRAY SONO_ARRAY;
    BEGIN
    V_MULTIVARRAY := SONO_ARRAY();
    V_MULTIVARRAY.EXTEND;
    V_MULTIVARRAY(1) := SONO_TABLE(SONO_ROW(1, SYSDATE));
    V_MULTIVARRAY(1).EXTEND;
    V_MULTIVARRAY(1)(1):= SONO_ROW(1, SYSDATE);
    V_MULTIVARRAY.EXTEND(1,1);
    V_MULTIVARRAY(2) := SONO_TABLE(SONO_ROW(1, SYSDATE));
    V_MULTIVARRAY(2).EXTEND;
    V_MULTIVARRAY(1)(2):= SONO_ROW(1, SYSDATE);
    V_MULTIVARRAY(2)(2):= SONO_ROW(1, SYSDATE);
    V_MULTIVARRAY(2)(1):= SONO_ROW(1, SYSDATE);
    END;
    Andrey

  • Possible bug: Saving array with extended and double precision to spreadshee​t

    If one concatenates a double precision array and an extended precision array with the "build array" vi and then saves using "Write to Spreadsheet File" vi any digits to the right of the decimal place are set to zero in the saved file. This happens regardless of the format signifier input (e.g. %.10f) to the  "Write to Spreadsheet File" vi.
    I am on Vista Ultimate 32 bit and labview 9.0
    This is a possible bug that is easily circumvented by converting to one type before combining arrar to a spreadsheet. Nonetheless, it is a bug and it cost me some time.
    Solved!
    Go to Solution.
    Attachments:
    Spreadsheet save bug.vi ‏9 KB

    Hi JL,
    no, it's not a bug - it's a feature
    Well, if you would look more closely you would recognize the "Save to Spreadsheet" as polymorphic VI. As this polymorphic VI doesn't support EXT numbers internally (it only supports DBL, I64 and String) LabVIEW chooses the instance with most accuracy: I64 (I64 has 64 bits precision, DBL only 53...). So your options are:
    - set the instance to use as DBL (by right-click and "Select type...")
    - make a copy of this VI, save it with a different name and make it support EXT numbers (don't rework the polymorphic VI as you would break compatibility with other LV installations or future revisions)
    And yes, those coercion dots always signal some conversions - you should atleast check what's going on there...
    Message Edited by GerdW on 05-21-2010 10:01 PM
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Public class ArrayEx extends Array

    Hi, I'm very bad at OO programming, but I'm trying to learn.
    I want to add some functions to my Arrays, like checking if
    arrays contain a value (indexOf can be equal to 0, which is false,
    though actually I'm used to the loose data typing of as2, so this
    may not be quite true. Bear with me though, I want to learn how to
    extend a class). So I'm trying to write a class that extends the
    basic Array class.
    I am confused about the constructor, I want to mimic the
    behaviour of the Array class but I'm not sure if I need to write
    functions for each method of Array. Since my ArrayEx extends the
    Array class it should inherit the array functions right? So it
    should already have .pop() and .push() ext. defined? How should I
    write my constructor to store the data the same way as the Array
    class does though?
    Is there somewhere I can look at the internal Array class to
    figure out how it does it?
    What I have written so far appears at the bottom of the
    message. I include questions as comments.
    I hope someone can help me out. I'm sorry if I'm asking stuff
    that seems obvious. Thanks for your time.
    Jon

    I've found the solution to my second set of problems and
    since I chose to trouble you all with the question I thought I'd
    post the answer.
    First problem, I had declared the ArrayEx class as dynamic
    but not as public. Should read;
    dynamic public class ArrayEx extends Array{
    Second problem. An empty constructor function, by default,
    calls the parent constructor function with no arguements. Since I
    wanted to construct my new array class like the default array class
    i had to add some code to handle that.
    So here is the working class;

  • Extending Array class, get Error #1069: Property 0 not found with indexOf call

    I'm using inheritance to extend the Array class to create a Paths class that moves Sprites/MovieClips around on the screen. I'm getting an odd error on a call to indexOf. Here's the error:
    ReferenceError: Error #1069: Property 0 not found on Paths and there is no default value.
        at Array$/_indexOf()
        at Array/http://adobe.com/AS3/2006/builtin::indexOf()
        at Paths/Next()[D:\Stephen\Documents\Flash\TossGame\TossGameFirstPerson\Paths.as:40]
    Here's the relevant code in the Paths class:
        public class Paths extends Array
            private var cCurrentPath:Path;
            public function Next():Path
                var lArray:Array = this;
                var lNextIndex:int = indexOf(cCurrentPath) + 1;
                if (lNextIndex == length) lNextIndex = 0;
                var lPath:Path = lArray[lNextIndex];
                return lPath;
        } // class
    I get the error at the highlighted line. cCurrentPath is populated with a Path object which is the object located at position 0 of the this object (Paths). I've tried the following variants of the Next() function:
    public function Next():Path
         var lArray:Array = this;
          var lNextIndex:int = lArray.indexOf(cCurrentPath) + 1;
          if (lNextIndex == lArray.length) lNextIndex = 0;
          var lPath:Path = lArray[lNextIndex];
          return lPath;
    public function Next():Path
         var lArray:Array = this;
          var lNextIndex:int = this.indexOf(cCurrentPath) + 1;
          if (lNextIndex == this.length) lNextIndex = 0;
          var lPath:Path = lArray[lNextIndex];
          return lPath;
    public function Next():Path
         var lArray:Array = this;
          var lNextIndex:int = super.indexOf(cCurrentPath) + 1;
          if (lNextIndex == super.length) lNextIndex = 0;
          var lPath:Path = lArray[lNextIndex];
          return lPath;
    Same error happens whichever I try. Anyone got any ideas?
    Stephen
    Flash Pro CS3 (Version 9.0)

    Mark your class dynamic.
    public dynamic class Paths extends Array

  • Array of file variables

    I wanted to have an array of variables of type Text_IO.File_Type.
    So I declared:
    TYPE file_array IS VARRAY(20) of Text_IO.File_Type;
    f_array file_array;
    begin
         f_array(1) := Text_IO.Fopen('c:\file', 'w');
    This compiled but didn't work, the Fopen fails, all other Fopen's that are not with array variables worked.
    Any idea why?
    Thanks.
    --Bassem                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Your syntax is slightly wrong you must initialise and extend the array:
    declare
      TYPE file_array IS VARRAY(20) of Text_IO.File_Type;
      f_array file_array := file_array();
    begin
      f_array.extend;
      f_array(1) := Text_IO.Fopen('c:\file', 'w'); It will then work.

  • Using an array of primitive

    How can I truncate an array of (primitive) double?
    Is it like the following, or some more obviously legitimate way?
    double[] dArr=new double[12345678];
    dArr = Arrays.copyOf(dArr,7234567); I don't want to have both sizes allocated at the same time.
    Also, (not as important to me) can I extend this array?
    And this reminds me of another related question:
    Why can't java allocate heap space by itself without my
    having to use, e.g., -Xmx999m manually and guessingly?
    Or can it?
    Or am I missing some procedure?

    hillmi wrote:
    How can I truncate an array of (primitive) double?
    Is it like the following, or some more obviously legitimate way?
    double[] dArr=new double[12345678];
    dArr = Arrays.copyOf(dArr,7234567); I don't want to have both sizes allocated at the same time.
    Also, (not as important to me) can I extend this array? Extend NO.
    Make a new one YES, but both would be in memory at the same time.
    You could use an ArrayList with Double, then you could extend it.
    And this reminds me of another related question:
    Why can't java allocate heap space by itself without my
    having to use, e.g., -Xmx999m manually and guessingly? I do not believe it can.

  • Declaring an array that is populated with a for loop

    Hi Guys,
    i have an array declared like this at the top of my class:
    private int [] longTable     ={16,17,18,19,20,21,22};
    It gets accessed from within methods in the same class.
    I want to extend this array to go from 16 up to 124 in increments of 1, and do not want to hard code those values,
    I tried this code, but its giving errors including longTable cannot be resolved to a type...
    private int [] longTable = new longTable[125];
    for(int i=16; i<longTable.length; i++)
         longTable[i] =i;
    how should i go about this?

    I think you have to write every number til 124, because you cannot "change" the size of this array after declaration.
    try this then:
    private int[] something = new int[125];
    int at = 0;
    for(int i = 16; i < something.length; i++)
       something[at] = i;
        at++;
    This will hopefully give you a array holding 125 int numbers
    something[0] = 16
    something[1] = 17
    something[2] = 18
    something[3] = 19
    .... etc til 125
    is this what you wanted ?
    Edited by: hdMilo on Mar 26, 2008 7:51 AM

  • Help adding to an array

    Hello,
    I've added an Add button to a GUI. This feature should enable users to add itemName, numberUnitsStock, unitPrice, and itemNumber(one more than the previous last item). Can anyone help? I'm thinking that I need to extend the array size first and then figure a way to get the aforementioned included in the array. Any help would be greatly appreciated.
    public class DVD6
              protected int itemNumber; // item number
              protected String itemName; // name of product
              protected int numberUnitsStock; // number of units in stock
              protected double unitPrice; // price of each unit
            // constructor initializes DVD with int, String, and double as argument
            public DVD6 (int itemNumber, String itemName, int numberUnitsStock, double unitPrice)
            this.itemNumber = itemNumber; // initializes itemNumber
              this.itemName = itemName; // initializes itemName
              this.numberUnitsStock = numberUnitsStock; // initializes numberUnitsStock
              this.unitPrice = unitPrice; // initializes unitPrice
              } // end constructor
                // method to set the item number
              public void setitemNumber (int itemNumber)
              itemNumber = itemNumber; // store the item number
              } // end method setitemNumber
                // method to retrieve the item number
            public int getitemNumber()
            return itemNumber;
            } // end method getitemNumber
            // method to set the name of product
                public void setitemName (String itemName)
                itemName = itemName; // store the name of product
                } // end method setitemName   
                // method to retrieve the itemName
            public String getitemName()
            return itemName;
            } // end method getitemName
            // method to set the number of units in stock
                public void setnumberUnitsStock (int numberUnitsStock)
                numberUnitsStock = numberUnitsStock; // store the number of units in stock
                } // end method setnumberUnitsStock   
                // method to retrieve the number of units in stock
            public int getnumberUnitsStock()
            return numberUnitsStock;
            } // end method getnumberUnitsStock
            // method to set the price of each unit
                public void setunitPrice (double unitPrice)
                unitPrice = unitPrice; // store the price of each unit
                } // end method setunitPrice   
                // method to retrieve the price of each unit
            public double getunitPrice()
            return unitPrice;
            } // end method getunitPrice
                // method to retrieve the inventoryValue
                public double getinventoryValue()
                return (numberUnitsStock * unitPrice); // multiply numbers
                } // end method getinventoryValue   
                // method to get the value of entire inventory
                public static double getTotalValueOfAllInventory (DVD6 [] inv)
                   double tot = 0.0;
                     for (int i = 0; i < inv.length; i++)
                        tot += inv.getinventoryValue();
                   return tot;
              } // end method getTotalValueOfAllInventory
              public static DVD6[] sort(DVD6 [] inventory)
              DVD6 temp[] = new DVD6[1];
                   // sort
                   for (int j = 0; j < inventory.length - 1; j++)
                   for (int k = 0; k < inventory.length - 1; k++)
                        if (inventory[k].getitemName().compareToIgnoreCase(inventory[k+1].getitemName()) > 0 )
                             temp[0] = inventory[k];
                                  inventory[k] = inventory[k+1];
                                  inventory[k+1] = temp[0];
                             } // end if
                        } // end for
              } // end for
              return inventory;
              public String toString()
              StringBuffer sb = new StringBuffer();
                   sb.append("Item number: \t").append(itemNumber).append("\n");
                   sb.append("DVD Title: \t").append(itemName).append("\n");
                   sb.append("Units in stock: \t").append(numberUnitsStock).append("\n");
                   sb.append("Price of unit: \t").append(String.format("$%.2f%n", unitPrice));
                   sb.append("Inventory value of product: \t").append(String.format("$%.2f%n", getinventoryValue()));
                   return sb.toString();
    } // end class DVD6
    public class DVDs6 extends DVD6
        private String genre; // genre of DVD
          private double restockingFee; // percentage added to product's inventory value
           //constructor
         public DVDs6(String genre, int itemNumber, String itemName,
                     int numberUnitsStock, double unitPrice)
               super(itemNumber, itemName, numberUnitsStock, unitPrice);
              this.genre = genre;
         // method to set the genre of DVD
         public void setgenre (String genre)
         genre = genre; // store the genre
         } // end method setgenre
         // method to retrieve the genre
         public String getgenre()
         return genre;
         } // end method getgenre
         // method to retrieve the restockingFee
         public double getrestockingFee()
         return (super.getunitPrice() * 0.05);
         } // end method getrestockingFee   
         // Inventory value + restocking fee
         public double getinventoryValue()
            return super.getinventoryValue() + (super.getunitPrice() * 0.05);
         // String representation
         public String toString()
            StringBuffer sb = new StringBuffer();
              sb.append("DVD Genre:   \t").append(genre).append("\n");
              sb.append("Restocking fee:   \t").append(String.format("$%.2f%n", getrestockingFee()));
              sb.append(super.toString());
              return sb.toString();
    } // end class
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    public class DVD6Test
         static int itemDisplay = 0; // ActionEvent variable 
         // main method begins execution of Java application  
       public static void main ( String args[] )
              double total = 0; // variable to get entire inventory value
              JPanel bttnJPanel; // panel to hold buttons
              JLabel label; // JLabel for company logo
              // instantiate object     
          final DVDs6[] a = new DVDs6[5];
          a[0] = new DVDs6("Action/Drama" , 041, "Rocky", 20, 15.00);
          a[1] = new DVDs6("Action" , 006, "Braveheart", 20, 20.00);
          a[2] = new DVDs6("Action" , 001, "Armageddon", 10, 10.00);
          a[3] = new DVDs6("Action" , 060, "Scarface", 15, 18.00);
          a[4] = new DVDs6("Action" , 021, "Goodfellas", 5, 15.00);
          DVDs6 temp[] = new DVDs6[1];
          // sort
          for (int j = 0; j < a.length - 1; j++)
             for (int k = 0; k < a.length - 1; k++)
                if (a[k].getitemName().compareToIgnoreCase(a[k+1].getitemName()) > 0 )
                   temp[0] = a[k];
                   a[k] = a[k+1];
                   a[k+1] = temp[0];
                } // end if
             } // end for
          } // end for
              // value of entire inventory
              for (int i = 0; i < a.length; i++)
                        total += a.getinventoryValue();
              // setup buttons
              JButton firstBtn = new JButton("First"); // button to display first inventory item
              JButton prevBtn = new JButton("Previous"); // button to display previous inventory item
              JButton nextBtn = new JButton("Next"); // button to display next inventory item
              JButton lastBtn = new JButton("Last"); // button to display last inventory item
              JButton addBtn = new JButton("Add"); // button to add item to inventory
              JButton delBtn = new JButton("Delete"); // button to delete item from inventory
              JButton modBtn = new JButton("Modify"); // button to modify DVD item
              JButton saveBtn = new JButton("Save"); // button to save inventory to a .dat file
              JButton srchBtn = new JButton("Search"); // button to search for item by name
              // create and setup panel to hold buttons
              bttnJPanel = new JPanel();
              bttnJPanel.setLayout(new GridLayout(1, 4));
              bttnJPanel.add(firstBtn);
              bttnJPanel.add(prevBtn);
              bttnJPanel.add(nextBtn);
              bttnJPanel.add(lastBtn);
              bttnJPanel.add(addBtn);
              bttnJPanel.add(delBtn);
              bttnJPanel.add(modBtn);
              bttnJPanel.add(saveBtn);
              bttnJPanel.add(srchBtn);
              //JLabel constructor
    Icon logo = new ImageIcon("C:/logo.jpg"); // load graphic
    label = new JLabel(logo); // create logo label
    label.setText("Java Solutions Inc."); // set company name          
              // text area and frame setup for product display
              final JTextArea textArea;      
              textArea = new JTextArea(a[0] + "\n");           
              textArea.append("\nValue of entire inventory: " + new java.text.DecimalFormat("$0.00").format(total) + "\n\n");
              textArea.setEditable(false); // uneditable text
              JFrame dvdFrame = new JFrame(); // JFrame container
              dvdFrame.setLayout(new BorderLayout()); // set layout
              dvdFrame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); // add text area to frame
              dvdFrame.getContentPane().add(bttnJPanel, BorderLayout.SOUTH); // adds buttons to frame
              dvdFrame.getContentPane().add(label, BorderLayout.NORTH); // add company logo to JFrame
              dvdFrame.setTitle("DVD Inventory"); // title of frame
              dvdFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // terminate upon close
              dvdFrame.setSize(800, 575); // set size
              dvdFrame.setLocationRelativeTo(null); // set location
              dvdFrame.setVisible(true); // display the window     
         // inner class to handle button events
    firstBtn.addActionListener(new ActionListener() // register event handler
    public void actionPerformed(ActionEvent event) // process button event
    itemDisplay = 0;
    textArea.setText(a[itemDisplay] + "\n");
              prevBtn.addActionListener(new ActionListener() // register event handler
    public void actionPerformed(ActionEvent event) // process button event
                   --itemDisplay;
                        if (itemDisplay < 0)
                        itemDisplay = (itemDisplay + a.length) % a.length;
                        textArea.setText(a[itemDisplay]+"\n");
              nextBtn.addActionListener(new ActionListener() // register event handler
              public void actionPerformed(ActionEvent event) // process button event
                        itemDisplay++;
                        if (itemDisplay >= a.length)
                        itemDisplay = (itemDisplay) % a.length;
                        textArea.setText(a[itemDisplay]+"\n");     
              lastBtn.addActionListener(new ActionListener() // register event handler
              public void actionPerformed(ActionEvent event) // process button event
                   itemDisplay = a.length-1;
                        textArea.setText(a[itemDisplay]+"\n");
              addBtn.addActionListener(new ActionListener() // register event handler
              public void actionPerformed(ActionEvent event) // process button event
                        DVDs6[] as = new DVDs6[a.length + 1]; // increase array length
                        textArea.setText(new String());
         } // end method main          
    } // end class

    check this link,
    http://www.java2s.com/Tutorial/Java/0140__Collections/0160__ArrayList.htm
    U have lot of collections. always user like this
    List user=new ArrayList();
    user.add("username");
    This code helps u to make changes in future. In future, if u want to change from ArrayList to Vector then u can just easily make a modification like this.
    List user=new Vector();
    user.add("username");
    need to make changes only in the declaration part.

  • Array length field

    Any array type has a length field which is probably declared as
    final public static int length;
    I would like to see the definition of length field at the class level
    within the java source. I do not find any such definition in the javadocs generated for the class Array?

    Array instances do not extend the Array class. They are part of the JVMs built in types. Arrays are strange in this aspect because they are Object types but their class type is not defined by a class file.

  • Efficiently accumulating arrays

    Hello,
    I am attempting to acquire a reasonable amount of data (between 100000
    and 1000000 floats) that I would like to accumulate into an array of
    single-precision floats.
    Efficiency is important due to time requirements of the device that I
    am acquiring from.
    I have observed that using a large array size - such as those
    mentioned above - results in my program running considerably slower
    throughout. The array is pre-allocated to the correct size using
    "Initialize Array" and then elements are replaced one-by-one using
    "Replace array Subset". This I believe to be the most efficient way
    of doing it from what I have read, for example in:
    http://zone.ni.com/devzone/conceptd.nsf/2d17d611efb58b22862567a9006ffe76/979f737147fd5c01862569f3
    00638674?OpenDocument
    Figure 2 on that page is quite similar to what I have (although much
    simplified). For each iteration of the loop I have my array wired to
    "Replace Array Subset", with the output wired to a local variable of
    the input array.
    Is there any reason why Labview should perform so poorly with large
    array sizes? My suspicion is that a copy of the entire array or a
    size check is being performed somewhere, but neither should be
    necessary in this case.
    If anyone could offer advice as to how to accumulate data into an
    array more efficiently I would be most grateful.
    I am using Labview 6.1
    Regards,
    Stephen

    > being received in blocks of 20 bytes which I then cast to a U32 array
    > so that I can "Byte-Swap" and "Word-Swap" before casting to
    > single-precision floats to extract the 5 floats which are the real
    > data. Each float is then appended to an array (since each of the 5
    > floats represents a different value) and then the 5 arrays are passed
    > to the next iteration using shift-registers as suggested by Mads.
    >
    > I am aware that casting is inefficient in Labview as it makes a copy
    > of the data(?), but it seems unavoidable in this case as I must
    > perform byte-swapping and Labview will only byte-swap integers, even
    > though I really want a byte-swapped float! I could move the
    > byte-swapping out of the acquisition phase, but this should be a
    > linear problem and so would not cause my program to slow down as it
    > does.
    It is probably just terminology, but here are some comments. After
    casting your 5 U32s to 5 floats, you say you extract the data and append
    it to an array. If you are truly using build array, then you are
    resizing the big array each time through the loop.
    Here is what you should try instead. Before starting the loop use
    Initialize Array to build a suitably sized buffer of zeros or other
    initialized value and wire that to your shift register. Inside the loop
    use Replace Array Subset to put all five floats from your array into the
    large array at the correct offset, or in older LVs, use five index nodes
    and five replaces, or use a for loop that autoindexes your small array,
    running five iterations, and does an Element Replace on the large array
    at the correct location.
    If you don't know how much data will arrive before entering the loop,
    then take a guess and inside the loop extend the array using Reshape
    Array once in awhile to add another couple thousand elements. You will
    also need to shrink the array after the loop, again using reshape.
    The key here is that resizing a big array gets more and more expensive
    as it gets larger. If you resize the array each iteration of the loop,
    this is far more expensive than the occasional resize, say each 1000
    elements, which is still more expensive that one resize before the loop
    begins.
    If this doesn't help, it might help if you were to post the VI or a
    picture of the VI diagram.
    Greg Mckaskle

  • PL/SQL Automatic Constraint Handler(Code)

    For those interested...
    I created the following database code that automatically does the constraint check/return error message for you.
    You could even take this a step further and create your own message repository...
    This guy even grabs/checks for foreign key violations:
    First part of code builds/returns dictionary data constraints for table that you specify.
    It then loads this data into object type.
    This object type will be referenced later in the database trigger that you create for table where you want to validate constraints
    return DbCons_documents_Array
    as
    dbdata DbCons_documents_Array := DbCons_documents_Array();
    i NUMBER := 1;
    begin
    FOR cns_rec IN(select child.child_cons_name clchild_cons_name,
    child.parent_cons_name clparent_cons_name,
    child.child_columns clchild_columns,
    parent.parent_cons_name pparent_cons_name,
    parent.parent_tname pparent_tname,
    child.child_tname clchild_tname,
    CONCAT(CONCAT('"',replace(replace(parent.parent_columns,'"',''),'''','')),'"') pparent_columns,
    child.parent_cons_type pparent_cons_type
    --CONCAT(CONCAT('''',web_form_array(find_web_frm_val).db_col_value),'''');
    FROM (
    select a.table_name child_tname,
    a.constraint_name child_cons_name,
    NVL(b.r_constraint_name,a.constraint_name) parent_cons_name,
    b.constraint_type parent_cons_type,
    max(decode(position, 1, '"'||column_name||'"',NULL)) ||
    max(decode(position, 2,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position, 3,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position, 4,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position, 5,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position, 6,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position, 7,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position, 8,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position, 9,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position,10,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position,11,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position,12,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position,13,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position,14,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position,15,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position,16,', '||'"'||column_name||'"',NULL))
    child_columns
    from user_cons_columns a, user_constraints b
    where a.constraint_name = b.constraint_name
    and b.constraint_type IN ( 'U', 'R' )
    --and nvl(B.r_constraint_name,B.constraint_name) = A.constraint_name
    -- and nvl(a.r_owner,a.owner) = b.owner
    group by a.table_name, a.constraint_name, b.r_constraint_name,b.constraint_type ) child,
    ( select a.constraint_name parent_cons_name,
    a.table_name parent_tname,
    max(decode(position, 1, '"'||column_name||'"',NULL)) ||
    max(decode(position, 2,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position, 3,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position, 4,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position, 5,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position, 6,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position, 7,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position, 8,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position, 9,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position,10,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position,11,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position,12,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position,13,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position,14,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position,15,', '||'"'||column_name||'"',NULL)) ||
    max(decode(position,16,', '||'"'||column_name||'"',NULL))
    parent_columns
    from user_cons_columns a, user_constraints b
    where a.constraint_name = b.constraint_name
    and b.constraint_type in ( 'P', 'U', 'R' )
    group by a.table_name, a.constraint_name ) parent
    where child.parent_cons_name = parent.parent_cons_name
    and child.child_tname = upper('YOUR TABLE NAME HERE')
    LOOP
    dbdata.extend(i);
    dbdata(i) := cdrl5.dbconstraint_documents_rec(cns_rec.pparent_cons_name,cns_rec.clchild_tname,cns_rec.pparent_tname,cns_rec.pparent_columns,cns_rec.pparent_cons_type);
    --dbdata(i) := '';
    -- dbdata(i) := dbconstraint_rec('test','test','test','test');
    --v_sql :=
    -- dbdata(i).constraint_name;
    i := i+1;
    END LOOP;
    FOR d IN 1..dbdata.COUNT
    LOOP
    IF dbdata(d).constraint_name IS NULL
    THEN
    dbdata.delete(d);
    END IF;
    END LOOP;
    -- dbdata.delete;
    return dbdata;
    END;
    Second part is code that is in trigger of table you are inserting into. Note that you have to store the table name/column name(that make up the constraint)/actual form values into pl/sql table:
    DECLARE
    v_sql VARCHAR2(32000);
    v_literal_value VARCHAR2(100);
    v_error_relay VARCHAR2(4000);
    v_db_values NUMBER := 1;
    v_dup_count NUMBER;
    nforeign_key EXCEPTION;
    TYPE DupRecordType IS REF CURSOR;
    dup_rec_cv DupRecordType;
    dbdata DbCons_Documents_Array := DbCons_Documents_Array(cdrl5.dbconstraint_documents_rec(null,null,null,null,null));
    TYPE tokenTableType is TABLE of varchar2(4000) -- table for Stringtoken
    index by binary_integer;
    tokenChar VARCHAR2(4000) := '," ';
    tokens tokenTableType;
    vCnt integer := 1;
    myLine varchar2(4000) := null;
    Line varchar2(4000) := null;
    vPos integer := 1;
    TYPE form_rec IS RECORD
    table_name VARCHAR2(100),
    db_column VARCHAR2(100),
    db_col_value VARCHAR2(1000)
    TYPE form_type IS TABLE OF form_rec
    INDEX BY binary_integer;
    web_form_array form_type;
    BEGIN
    dbdata.DELETE;
    -- IF :new.DOC_ID IS NOT NULL
    -- THEN
    NOTE: Load the below table(with values specified) for each table constraint
    web_form_array(v_db_values).table_name :=
    'YOUR TABLE NAME';
    web_form_array(v_db_values).db_column :=
    'YOUR FIELD NAME';
    web_form_array(v_db_values).db_col_value :=
    :new.;
    v_db_values := v_db_values +1;
    FOR cns_rec IN(select *
    from TABLE ( cast( documents_cons_dml() as DbCons_documents_Array ))
    LOOP
    line :=
    cns_rec.constraint_where;
    v_sql := 'SELECT count(*) FROM '||cns_rec.constraint_column;
    IF INSTR(line,',',1,1) <= 0
    THEN
    FOR find_web_frm_val IN 1..web_form_array.COUNT
    LOOP
    IF cns_rec.table_name = web_form_array(find_web_frm_val).table_name
    AND replace(line,'"','') = web_form_array(find_web_frm_val).db_column
    THEN
    v_literal_value :=
    CONCAT(CONCAT('''',web_form_array(find_web_frm_val).db_col_value),'''');
    v_sql := v_sql||' WHERE '||' '||web_form_array(find_web_frm_val).db_column||' = '||v_literal_value;
    END IF;
    END LOOP;
    ELSE
    while (vPos <= length(line))
    loop
    if (length(replace(tokenChar,substr(line, vPos, 1), '')) = length(tokenChar))
    then
    myLine := myLine || substr(line, vPos, 1);
    elsif (myLine is not NULL) then
    tokens(vCnt) := myLine;
    FOR find_web_frm_val IN 1..v_db_values
    LOOP
    IF cns_rec.table_name = web_form_array(find_web_frm_val).table_name
    AND MYLine = web_form_array(find_web_frm_val).db_column
    THEN
    v_literal_value :=
    CONCAT(CONCAT('''',web_form_array(find_web_frm_val).db_col_value),'''');
    END IF;
    end loop;
    IF vCnt = 1
    THEN
    v_sql := v_sql||' WHERE '||' '||myLine||' = '||v_literal_value;
    ELSE
    v_sql := v_sql||' AND '||' '||myLine||' = '||v_literal_value;
    END IF;
    myLine := null;
    vCnt := vCnt + 1;
    end if;
    vPos := vPos + 1;
    end loop;
    if (myLine is not NULL) then
    tokens(vCnt) := myLine;
    end if;
    vCnt := 1;
    vPos := 1;
    END IF;
    OPEN dup_rec_cv FOR v_sql;
    FETCH dup_rec_cv
    INTO v_dup_count;
    CLOSE dup_rec_cv;
    IF cns_rec.column_position = 'R'
    THEN
    IF v_dup_count <= 0
    THEN
    v_error_relay :=
    'The form field value for Database Column '||' '||line||' '||' that was entered does not exist';
    RAISE nforeign_key;
    END IF;
    ELSIF cns_rec.column_position = 'U'
    THEN
    IF v_dup_count > 0
    THEN
    RAISE DUP_VAL_ON_INDEX;
    END IF;
    END IF;
    -- commit_trans(v_dup_count);
    -- INSERT INTO test
    -- values(line||' '||INSTR(line,',',1,1));
    -- VALUES(cns_rec.constraint_name||' '||cns_rec.table_name||' '||cns_rec.constraint_column||' '||cns_rec.constraint_where);
    -- values(v_sql||' '||vPos||' '||length(line));
    -- VALUES(web_form_array(i).table_name||' '||CONCAT(CONCAT('''',web_form_array(i).db_col_value),'''')||' '||i);
    --commit;
    -- i := i+1;
    END LOOP;
    EXCEPTION
    WHEN DUP_VAL_ON_INDEX
    THEN
    raise_application_error(-20101, 'Attempted to update duplicate. Cannot update '||:new.);
    WHEN nforeign_key
    THEN raise_application_error(-20101, v_error_relay||' '||' YOUR MESSAGE HERE '||:new.);
    END;

    Mark:
    Ordinarily, I not really a critical guy, but that thing is such a mess that I have to comment. I won't mention the complete lack of bind variables (which leads to the shared pool and hard parsing concerns), but as posted it won't even compile. I had some time to kill, so.
    For starters, the big query in your function gets:
    ORA-01467: sort key too long
    on my 9.2.0.6 instance with 16K blocksize, and on my 9.2.0.1 instance with an 8K blocksize. Interestingly, it does work on my 8.1.7.4 instance with 8K blocks. So, I had to limit it to 15 columns.
    You give no function name at all. Based on the trigger code, I assume the function should be documents_cons_dml. I also added a paramter to pass the table name since one could conceivably have more than one table in an application.
    I also took the liberty of fixing your extend problem. In your code, you extend the array by one in the first iteration through the loop, by two in the second and so on. Which is why you need the delete loop at the end.
    There is no definition for the DbCons_documents_Array that the function returns, so I assumed something like:
    SQL> CREATE TYPE dbconstraint_documents_rec AS OBJECT (
      2     constraint_name   VARCHAR2(30),
      3     table_name        VARCHAR2(30),
      4     constraint_column VARCHAR2(30),
      5     constraint_where  VARCHAR2(4000),
      6     column_position   VARCHAR2(1) );
      7  /
    Type created.
    SQL> CREATE TYPE DbCons_documents_Array AS
      2     VARRAY(50) OF dbconstraint_documents_rec;
      3  /
    Type created.I used the names that you used in the trigger, although the names don't seem to match with the column contents, must be code re-use.
    So, now the function looks like:
    SQL> CREATE FUNCTION documents_cons_dml (p_table_name IN VARCHAR2)
      2    RETURN DbCons_documents_Array AS
      3
      4     dbdata DbCons_documents_Array := DbCons_documents_Array();
      5     i NUMBER := 1;
      6  BEGIN
      7     FOR cns_rec IN(SELECT child.child_cons_name clchild_cons_name,
      8                           child.parent_cons_name clparent_cons_name,
      9                           child.child_columns clchild_columns,
    10                           parent.parent_cons_name pparent_cons_name,
    11                           parent.parent_tname pparent_tname,
    12                           child.child_tname clchild_tname,
    13                           CONCAT(CONCAT('"',REPLACE(REPLACE(parent.parent_columns,'"',''),'''','')),'"') pparent_columns,
    14                           child.parent_cons_type pparent_cons_type
    15                    FROM (SELECT a.table_name child_tname,
    16                                 a.constraint_name child_cons_name,
    17                                 NVL(b.r_constraint_name,a.constraint_name) parent_cons_name,
    18                                 b.constraint_type parent_cons_type,
    19                                 MAX(DECODE(position, 1, '"'||column_name||'"',NULL)) ||
    20                                 MAX(DECODE(position, 2,', "'||column_name||'"',NULL)) ||
    21                                 MAX(DECODE(position, 3,', "'||column_name||'"',NULL)) ||
    22                                 MAX(DECODE(position, 4,', "'||column_name||'"',NULL)) ||
    23                                 MAX(DECODE(position, 5,', "'||column_name||'"',NULL)) ||
    24                                 MAX(DECODE(position, 6,', "'||column_name||'"',NULL)) ||
    25                                 MAX(DECODE(position, 7,', "'||column_name||'"',NULL)) ||
    26                                 MAX(DECODE(position, 8,', "'||column_name||'"',NULL)) ||
    27                                 MAX(DECODE(position, 9,', "'||column_name||'"',NULL)) ||
    28                                 MAX(DECODE(position,10,', "'||column_name||'"',NULL)) ||
    29                                 MAX(DECODE(position,11,', "'||column_name||'"',NULL)) ||
    30                                 MAX(DECODE(position,12,', "'||column_name||'"',NULL)) ||
    31                                 MAX(DECODE(position,13,', "'||column_name||'"',NULL)) ||
    32                                 MAX(DECODE(position,14,', "'||column_name||'"',NULL)) ||
    33                                 MAX(DECODE(position,15,', "'||column_name||'"',NULL)) child_columns
    34                          FROM user_cons_columns a, user_constraints b
    35                          WHERE a.constraint_name = b.constraint_name and
    36                                b.constraint_type IN ( 'U', 'R' )
    37                          GROUP BY a.table_name, a.constraint_name,
    38                                   b.r_constraint_name,b.constraint_type ) child,
    39                         (SELECT a.constraint_name parent_cons_name,
    40                                 a.table_name parent_tname,
    41                                 MAX(DECODE(position, 1, '"'||column_name||'"',NULL)) ||
    42                                 MAX(DECODE(position, 2,', "'||column_name||'"',NULL)) ||
    43                                 MAX(DECODE(position, 3,', "'||column_name||'"',NULL)) ||
    44                                 MAX(DECODE(position, 4,', "'||column_name||'"',NULL)) ||
    45                                 MAX(DECODE(position, 5,', "'||column_name||'"',NULL)) ||
    46                                 MAX(DECODE(position, 6,', "'||column_name||'"',NULL)) ||
    47                                 MAX(DECODE(position, 7,', "'||column_name||'"',NULL)) ||
    48                                 MAX(DECODE(position, 8,', "'||column_name||'"',NULL)) ||
    49                                 MAX(DECODE(position, 9,', "'||column_name||'"',NULL)) ||
    50                                 MAX(DECODE(position,10,', "'||column_name||'"',NULL)) ||
    51                                 MAX(DECODE(position,11,', "'||column_name||'"',NULL)) ||
    52                                 MAX(DECODE(position,12,', "'||column_name||'"',NULL)) ||
    53                                 MAX(DECODE(position,13,', "'||column_name||'"',NULL)) ||
    54                                 MAX(DECODE(position,14,', "'||column_name||'"',NULL)) ||
    55                                 MAX(DECODE(position,15,', "'||column_name||'"',NULL)) parent_columns
    56                          FROM user_cons_columns a, user_constraints b
    57                          WHERE a.constraint_name = b.constraint_name and
    58                                b.constraint_type IN ( 'P', 'U', 'R' )
    59                          GROUP BY a.table_name, a.constraint_name ) parent
    60                    WHERE child.parent_cons_name = parent.parent_cons_name and
    61                          child.child_tname = upper(p_table_name)) LOOP
    62        dbdata.extend;
    63        dbdata(i) := dbconstraint_documents_rec(cns_rec.pparent_cons_name,
    64                                                cns_rec.clchild_tname,
    65                                                cns_rec.pparent_tname,
    66                                                cns_rec.pparent_columns,
    67                                                cns_rec.pparent_cons_type);
    68        i := i+1;
    69     END LOOP;
    70     RETURN dbdata;
    71  END;
    72  /
    Function created.
    SQL> CREATE TABLE t (ID NUMBER PRIMARY KEY, descr VARCHAR2(10));
    Table created.
    SQL> CREATE TABLE t1 (idt1 NUMBER PRIMARY KEY, descr VARCHAR2(10));
    Table created.
    SQL> ALTER TABLE t ADD CONSTRAINT t_fk
      2  FOREIGN KEY (id) REFERENCES t1 (idt1);
    Table altered.Now for the trigger. Once I got rid of the schema owner cdrl5 in the dbconstraint_documents_rec call it actually compiled first time. So, my trigger looks like:
    SQL> CREATE OR REPLACE TRIGGER t_bi
      2  BEFORE INSERT ON t
      3  FOR EACH ROW
      4  DECLARE
      5     v_sql VARCHAR2(32000);
      6     v_literal_value VARCHAR2(100);
      7     v_error_relay VARCHAR2(4000);
      8     v_db_values NUMBER := 1;
      9     v_dup_count NUMBER;
    10     nforeign_key EXCEPTION;
    11
    12     TYPE DupRecordType IS REF CURSOR;
    13     dup_rec_cv DupRecordType;
    14
    15     dbdata DbCons_Documents_Array := DbCons_Documents_Array(dbconstraint_documents_rec(null,null,null,null,null));
    16
    17     TYPE tokenTableType IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;
    18     tokenChar VARCHAR2(4000) := '," ';
    19     tokens tokenTableType;
    20     vCnt INTEGER := 1;
    21     myLine VARCHAR2(4000) := NULL;
    22     Line VARCHAR2(4000) := NULL;
    23     vPos INTEGER := 1;
    24
    25     TYPE form_rec IS RECORD (
    26        table_name VARCHAR2(100),
    27        db_column VARCHAR2(100),
    28        db_col_value VARCHAR2(1000));
    29
    30     TYPE form_type IS TABLE OF form_rec INDEX BY BINARY_INTEGER;
    31     web_form_array form_type;
    32
    33  BEGIN
    34     dbdata.DELETE;
    35  -- NOTE: Load the below table(with values specified) for each table constraint
    36
    37     web_form_array(v_db_values).table_name := 'T';
    38     web_form_array(v_db_values).db_column := 'ID';
    39     web_form_array(v_db_values).db_col_value := :new.ID;
    40     v_db_values := v_db_values +1;
    41
    42     FOR cns_rec IN(SELECT *
    43                    FROM TABLE ( CAST(documents_cons_dml('T') AS DbCons_documents_Array ))) LOOP
    44        line := cns_rec.constraint_where;
    45        v_sql := 'SELECT count(*) FROM '||cns_rec.constraint_column;
    46        IF INSTR(line,',',1,1) <= 0 THEN
    47           FOR find_web_frm_val IN 1 .. web_form_array.COUNT LOOP
    48              IF cns_rec.table_name = web_form_array(find_web_frm_val).table_name AND
    49                 REPLACE(line,'"','') = web_form_array(find_web_frm_val).db_column THEN
    50
    51                 v_literal_value :=CONCAT(CONCAT('''',web_form_array(find_web_frm_val).db_col_value),'''');
    52                 v_sql := v_sql||' WHERE '||' '||web_form_array(find_web_frm_val).db_column||' = '||v_literal_value;
    53              END IF;
    54           END LOOP;
    55        ELSE
    56           WHILE (vPos <= LENGTH(line)) LOOP
    57              IF (LENGTH(REPLACE(tokenChar,substr(line, vPos, 1), '')) = LENGTH(tokenChar)) THEN
    58                 myLine := myLine || substr(line, vPos, 1);
    59              ELSIF (myLine IS NOT NULL) THEN
    60                 tokens(vCnt) := myLine;
    61                 FOR find_web_frm_val IN 1 .. v_db_values LOOP
    62                    IF cns_rec.table_name = web_form_array(find_web_frm_val).table_name AND
    63                          MYLine = web_form_array(find_web_frm_val).db_column THEN
    64                       v_literal_value := CONCAT(CONCAT('''',web_form_array(find_web_frm_val).db_col_value),'''');
    65                    END IF;
    66                 END LOOP;
    67                 IF vCnt = 1 THEN
    68                    v_sql := v_sql||' WHERE '||' '||myLine||' = '||v_literal_value;
    69                 ELSE
    70                    v_sql := v_sql||' AND '||' '||myLine||' = '||v_literal_value;
    71                 END IF;
    72                 myLine := null;
    73                 vCnt := vCnt + 1;
    74              END IF;
    75              vPos := vPos + 1;
    76           END LOOP;
    77
    78           IF (myLine IS NOT NULL) THEN
    79              tokens(vCnt) := myLine;
    80           END IF;
    81           vCnt := 1;
    82           vPos := 1;
    83        END IF;
    84
    85        OPEN dup_rec_cv FOR v_sql;
    86        FETCH dup_rec_cv INTO v_dup_count;
    87        CLOSE dup_rec_cv;
    88        IF cns_rec.column_position = 'R' THEN
    89           IF v_dup_count <= 0 THEN
    90              v_error_relay := 'The form field value for Database Column '||' '||line||' '||' that was entered does not exist';
    91              RAISE nforeign_key;
    92           END IF;
    93        ELSIF cns_rec.column_position = 'U' THEN
    94           IF v_dup_count > 0 THEN
    95              RAISE DUP_VAL_ON_INDEX;
    96           END IF;
    97        END IF;
    98     END LOOP;
    99  EXCEPTION
    100     WHEN DUP_VAL_ON_INDEX THEN
    101        raise_application_error(-20101, 'Attempted to update duplicate. Cannot update '||:new.ID);
    102     WHEN nforeign_key THEN
    103        raise_application_error(-20101, v_error_relay||' '||' YOUR MESSAGE HERE '||:new.ID);
    104  END;
    105  /
    Trigger created.So, lets try this puppy out.
    SQL> INSERT INTO t1 VALUES (1, 'T1 ONE');
    1 row created.
    SQL> COMMIT;
    Commit complete.I want at least one valid value to make sure I can actually insert something without dying on the trigger.
    SQL> INSERT INTO t VALUES (1, 'T One');
    1 row created.
    SQL> COMMIT;
    Commit complete.Which we can. Now lets test the Primary Key.
    SQL> INSERT INTO t VALUES (1, 'T One');
    INSERT INTO t VALUES (1, 'T One')
    ERROR at line 1:
    ORA-00001: unique constraint (OPS$ORACLE.SYS_C0027113) violatedOOPS, that's Oracle's message. Well, maybe it's because you are only checking cns_rec.column_position for R or U and my constraint is a P, and by the way, your function does not return the Primary Key for the table passed at all.
    So, lets try the foreign key:
    SQL> INSERT INTO t VALUES (2, 'T Two');
    INSERT INTO t VALUES (2, 'T Two')
    ERROR at line 1:
    ORA-02291: integrity constraint (OPS$ORACLE.T_FK) violated - parent key not foundOOPS. So, for every valid insert I am doing a huge amount of extra work, and I still get Oracle's errors when it's wrong. If I have screwed something up in the set-up, please feel free to post a working example exactly as I did here.
    John

Maybe you are looking for

  • Help for first install of macpro with osx server

    Hello to all it's my first message on this forum, i'm seeking for help because i'm kind of new with Mac systems. I'm gonna explain the problem So we are going to buy a mac pro and put 4*2To inside with raid 5 and osx server. The problem is that the c

  • Image content not defined in TileList

    I have two images on a canvas, one is directly on the canvas using inline code, the other is embedded in a tilelist. Both images render. When I click and drag the inline image, the drag proxy appears normally. When I click and drag the image in the t

  • DVD not read correctly: Medieval 2 will not start anymore (original disc)

    Hi everyone, sorry if i am posting this in the wrong part of the website but i really need help with something. I bought a new pc game ( Medieval 2 Total War ) and when i 1st installed it, it worked fine. The day after i went to play it again and whe

  • Error in creating GUID using com.sap.guid API's

    Hi    i am trying to create GUID using com.sap.guid API's. I've included the guidgenerator.jar in the classpath. I ran the following code. i got the "Caused by: java.lang.NoClassDefFoundError: com/sap/guid/GUIDGeneratorFactory " error. the code is pa

  • Reg: downloading of trial version.  SAP NetWeaver CE 7.2 - Server

    Hi, I tried downloading the sap netweaver trial version SAP NetWeaver CE 7.2 - Server.  It says  "Unfortunately we have trouble completing your download request. Please contact [email protected] for further support".  I wrote to them, several days ha