Passing collection or array to function: shallow copy or not?

Hello all,
When passing a collection or an array to a function, what is most used practice to store the given collection in some class member field: reference-copy or a shallow copy?
I believe it's frustrating to see that there is no real 'standard' about this: some developers copy the whole collection/array, others prefer to simply copy the reference. I tend to agree with the latter group:
- it's the user's responsibility if he wants the class to use a copied version instead of the 'original' version of the collection/array.
- most of the times, a copy is not needed, and therefor a shallow copy is pure waste of resources.
- when nothing is known about the given collection, and there are also no restrictions on the collection to be given, it could be everything: ArrayList? HashSet? SortedSet? AnUnknownImplementation?
reference copy:
class ComeClass
    private ArrayList list;
    public SomeClass(ArrayList list) { this.list = list; }
}shallow copy:
class ComeClass
    private List list;
    public SomeClass(List list) { this.list = new ArrayList(list); }
}What are your thoughts about this?

basically, it's how much access you want to provides.
public SomeClass(ArrayList list) { this.list = list; }to me, if some other class has a reference to the list object and start modifying it..Someclass internal data (the list) is also modified...thus breaking encapsulation.
yes, in multithread enviroment, sharing the list(by reference can lead to some hard bug to debug), so it;s much safer to copy (clone) the list. Java does this and provides you the MultiCaster class to make thing easier for you.
even with synchronization, there are issues you have to look at (such as deadlock)..you can synchronize the list, but can still run into a dead lock
list is synchronized in class A
class B have object (that's in list and call the list (wait due to class A synchronization)
list tries to invoke method of class B, but wait (class B is lock)..thus..deadlock.
it's a crued exapmle..but i think you get the point.
the saying is that to make a safer application..declare all you object immutable or restrict access to your private data. Of course, performance wise, we have to comprise sometime.
example..a list with over 500,000 objects..you might not want to to clone the reference.

Similar Messages

  • Passing pl/sql array to function

    Hi,
    I have a function which takes an array:
    create or replace
    FUNCTION execute_tests(
    leg_keys IN type_leg_key_array)
    RETURN BOOLEAN
    IS
    BEGIN
    leg_key_array is this:
    create or replace
    TYPE type_leg_key_array AS TABLE OF NUMBER(6, 3);
    I would like to test this funtion by passing it some array:
    DECLARE
    LEG_KEYS DEV_SWA30PRE.TYPE_LEG_KEY_ARRAY;
    V_RETURN BOOLEAN;
    BEGIN
    -- LEG_KEYS := NULL;
    v_Return := EXECUTE_TESTS(LEG_KEYS);
    END;
    What is wrong with the snippet above?
    Thanks

    Hi,
    user610868 wrote:
    Hi,
    I have a function which takes an array:
    create or replace
    FUNCTION execute_tests(
    leg_keys IN type_leg_key_array)
    RETURN BOOLEAN
    IS
    BEGIN
    leg_key_array is this:
    create or replace
    TYPE type_leg_key_array AS TABLE OF NUMBER(6, 3);
    I would like to test this funtion by passing it some array:
    DECLARE
    LEG_KEYS DEV_SWA30PRE.TYPE_LEG_KEY_ARRAY;
    V_RETURN BOOLEAN;
    BEGIN
    -- LEG_KEYS := NULL;
    v_Return := EXECUTE_TESTS(LEG_KEYS);
    END;
    What is wrong with the snippet above?Why do you think anything is wrong? Are you getting an error message? Post the complete error message, including line numbers. Does the error occur when you create the type, when you create the function, when you call the function, or someplace else?
    The only errors I see are probably due to how you chose to post it. For example, there is no RETURN or END statement in execute_tests.
    Did you create the type before trying to use it in the function?
    What is DEV_SWA30PRE? Is that a schema? Does that schema also contain the fucntion? Is that who is running the anonymous block? If there are other schemas involved, what are they? What are they doing? What privileges do they have on the type or the function?
    Post a complete test script that people can run to re-create the problem and test their ideas.

  • Passing 3d arrays to functions in C

    So.. I have a certain char array[8][3][30], declared as ***array, and allocated as the program progresses. I'd like to pass that to an external function, but GCC pukes out warnings that the type case isn't right, and anytime I access it in the function, it segfaults (basically, it doesn't pass properly).
    my function prototype:
    int parse_table(char ***table);
    and code to pass it:
    parse_table(table);
    anyone knowledgable on this?

    tardo wrote:main()
    char ***table;
    parse_table(table);
    use_table(table);
    parse_table(char ***table)
    // read one value from file
    // determine other two values from file input
    // allocate memory depending on values (varies with file input)
    use_table(char ***table)
    // programming homework (probably a tree)
    AHEM, so, I actually bothered to read this properly this time . If this is actually how you have your code structured, this is definitely a problem. Think about this: "table" is of type "char ***", correct? parse_table takes a type "char ***"... you have pass-by-value semantics here. So, essentially, parse_table will receive a COPY of an unitialized memory location. You will then set this local copy to the return of malloc (e.g. something lik table = malloc(/*stuff*/)). However, this is not affecting the table seen in main()! Essentially, you should have something like:
    int main() {
    char ***table = parse_table();
    /* rest of main */
    char *** parse_table() {
    /* Stuff that mallocs into local_table pointer */
    return local_table;
    Where, you malloc the stuff in parse_table, and return that pointer. Alternatively (and painfully), you could do something weird like:
    int main() {
    char ***table;
    parse_table(&table);
    /* rest of main */
    void parse_table(char ****table) { /* Note: four "asterisks", not three! */
    /* malloc evilness in here, with something like (*table) = malloc(/* stuff */) */
    (Don't do this, it's ugly and unnecessary)
    Just to be completely pendantic, check it this sample code I whipped up:
    #include <stdlib>
    #include <stdio>
    void evil_and_wrong(char *f) {
    printf("Memory location we'd allocate to (evil_and_wrong): %un", &f);
    f = (char*)malloc(5*sizeof(char));
    f[0]='p';
    void my_alloc_f(char **f) {
    printf("Memory location we'd allocate to (my_alloc_f): %un", f);
    (*f) = (char*)malloc(5*sizeof(char));
    (*f)[0]='p';
    char * nicer_my_alloc_f() {
    char *local_f = (char*) malloc(5*sizeof(char));
    local_f[0]='p';
    return local_f;
    int main() {
    char *f;
    printf("ACTUAL Memory location: %un", &f);
    evil_and_wrong(f);
    // We won't try anything with "f" here, since it'll segault...
    my_alloc_f(&f);
    printf("Should see: %un", 'p');
    printf("See: %un", f[0]);
    free(f);
    f = nicer_my_alloc_f();
    printf("See: %un", f[0]);
    free(f);
    return 0;
    Look at the outputted memory locations, and think about the fact you're trying to store the address of the allocated memory...

  • Passing a Variant array to ArrayToImage Function

    Hi,
    I need help passing a Variant array to the ArrayToImage function in the NI Vision library.
    I have no problems using the ImageToArray function - but when going back to the CWIMAQImage type the application throws an exception.
    Are there any code samples for doing this?
    Thanks!

    Hello,
    Thank you for posting to the NI forums! Try calling the ImageToArray function then immediately passing the resultant array back to ArrayToImage. That will determine whether the ArrayToImage function is causing the error, or the array that is passed into it. Can you post a small sample of how you call the ArrayToImage function and the errors that are thrown?
    Thanks,
    Maclean G.
    Applications Engineering
    National Instruments

  • The System.arraycopy Functionality and copying array question

    When created arrays such as String[] myStringArray (for example), is it general good practice to use the System.arraycopy function to copy the array?
    Why isn't it good practice to use equal instead? Would this work just as well?
    String[] myStringArray = new String[] { "My", " Test"};
    String[] myStringArrayCopy = new String[myStringArray.length};
    myStringArrayCopy = myStringArrayCopy;Or is that just going to make them the same element in memory and if I change myStringArray in antoher part of the program that means myStringArrayCopy will change as well since it is the same thing?

    Youre right, the equals sign just assigns the new array same reference in memory as the old array so they are pointing to the same data.
    Im 90% sure of that.
    If you want to work with an array without changing the original array id suggest using the System.arraycopy method. If you dont mind the contents changing then use the = sign..(but then why use a new array at all?)
    Hope this helps, if not theres loads of more experienced people on the boards...
    Ocelot

  • Is it OK to use clone when you only need shallow copy?

    I created copy contructors for all of my libraries classes because I was afraid of using the clone() method.
    However, my copy constructors create shallow copies of the objects - which is probably the same as using clone().
    Before I go deleting all the copy constructors from all of my classes...
    Is there any reason not to use clone() in this case? Are there any gotchas with clone() when it comes to just a simple shallow copy (perhaps with simple arrays, simple object arrays, or collections) ?
    Thanks

    Another thing worth mentioning is that if you really need to have more control of the clone process, then just over-ride the clone method. In most cases the default Object.clone() method should be enough. BTW don't forget to use the Clonable interface for your class.
    The whole notion of a copy constructor is much more a C++ thing.

  • Pass collections into to select query on IN caluse

    Hi friends,
    I wanted to pass collections in to select query IN caluse .
    Eg..
    Declare
    type tab is table of varchar2(25);
    v_tab tab:
    type tab1 is table of varchar2(25);
    v_tab1 tab:
    Begin
    select ename into v_tab from emp where deptno in (10,20,30);
    select location into v_tab1 emp_hist where ename in ( v_tab1 ); -- here where i wnt to pass the collections
    End;
    i dont want to write an loop to do this , i like to use only collections ? any idea how
    thanks in advance .
    Raj

    Hi Raj,
    In the examples above you will need to have a type declared in the database, however you can create a pipelined function to do what you want... something like this,
    SQL> Create OR Replace Package My_Types Is
      2 
      3     Type enames_tab Is Table Of Varchar2(50);
      4 
      5  End My_Types;
      6  /
    Package created
    SQL> Create OR Replace Function lookup_ename Return my_types.enames_tab
      2     Pipelined Is
      3     v_row   my_types.enames_tab;
      4     cur     Sys_Refcursor;
      5     v_ename Varchar2(50);
      6  Begin
      7     v_row := my_types.enames_tab();
      8     Open cur For
      9        SELECT ename
    10          FROM emp
    11         WHERE ename IN ('SMITH', 'JAMES', 'WARD');
    12     Loop
    13        Fetch cur
    14           INTO v_ename;
    15        Exit When cur%Notfound;
    16        v_row.Extend;
    17        v_row(v_row.Count) := v_ename;
    18        Pipe Row(v_row(v_row.Count));
    19     End Loop;
    20     Return;
    21  End;
    22  /
    Function created
    SQL> Set Serveroutput on;
    SQL> Declare
      2     v_tab my_types.enames_tab;
      3  Begin
      4     SELECT ename Bulk Collect
      5       INTO v_tab
      6       FROM emp
      7      WHERE ename IN (SELECT *
      8                        FROM Table(lookup_ename));
      9 
    10     For i IN v_tab.First .. v_tab.Last Loop
    11        dbms_output.put_line(v_tab(I));
    12     End Loop;
    13  End;
    14  /
    SMITH
    WARD
    JAMES
    PL/SQL procedure successfully completedRegards,
    Christian Balz

  • How tp pass javascript variables/arrays to a servlet?

    Plz help me in passing javascript variables/arrays to a servlet

    Hi,
    I am creating table rows & columns containg text fields dynamically as follows:
    function addRowToTable()
    var tbl = document.getElementById('tblSample');
    var lastRow = tbl.rows.length;
    // if there's no header row in the table, then iteration = lastRow + 1
    var iteration = lastRow;
    var row = tbl.insertRow(lastRow);
    // right cell
    var cellRight = row.insertCell(0);
    var el = document.createElement('input');
    el.type = 'text';
    el.name = 'txtRow' + iteration;
    el.id = 'txtRow' + iteration;
    el.size = 20;
    cellRight.appendChild(el);
    Now i am calling function addRowToTable() from jsp page as + key is pressed to add rows dynamically.
    So as per rows different textfields are also getting created dynamically with different id & name.
    Now i am getting session attributes containing the values for textfields from servlet.
    but i am not able to map the values for dynamic textfields getting created?
    I want to print values in appropriate fields.
    Plz help me.

  • Passing parameters to event triggered functions

    hi all,
    i have created a button and added EventListener.
    as mybutton.addEventListener(MouseEvent.CLICK,clickSt art);
    when i implement the clickStart (event:MouseEvent) function i
    want to pass
    an array ,a String to this function as parameters .how can i
    do this.
    is it possible or not.
    thanx.

    Well, not in that way.
    The function automatically receives a parameter when you
    create a callback with that function by "addEventListener", such
    parameter is datatyped as the event type you defined in the
    callback, in your case "MouseEvent". If you want to pass more data
    when the function is called then you have to create your own event
    class because almost all events just inform when something has
    happened and send limited information. You can check the
    documentation about creating a custom event class, there is a lot
    of info about the topic.

  • How can I pass an empty array to a parameter of type PLSQLAssociativeArray

    How can I pass an empty array to a parameter of type PLSQLAssociativeArray in VB? I defined the parameter like this
    Dim myArray() as String = new String() {}
    Dim myPara as new Oracle.DataAccess.Client.OracleCollectionType.PLSQLAssociativeArray
    myPara = 0
    myPara.Value = myArray
    When I execute my stored procedure giving the above parameter, I got error saying OracleParameter.Value is invalid.
    I have tried to give it the DBNull.Value, but it doesn't work either.
    Note: everything works fine as long as myArray has some item in there. I just wonder how I can make it works in case I have nothing.
    Thank you,

    How can I pass an empty array to a parameter of type PLSQLAssociativeArray in VB? I defined the parameter like this
    Dim myArray() as String = new String() {}
    Dim myPara as new Oracle.DataAccess.Client.OracleCollectionType.PLSQLAssociativeArray
    myPara = 0
    myPara.Value = myArray
    When I execute my stored procedure giving the above parameter, I got error saying OracleParameter.Value is invalid.
    I have tried to give it the DBNull.Value, but it doesn't work either.
    Note: everything works fine as long as myArray has some item in there. I just wonder how I can make it works in case I have nothing.
    Thank you,

  • How can i declare 2 or more dimension array as function parameter???

    I am new to Objective-C and Cocoa. and now I have a problem.
    I want to send 2 dimension array to function but it cannot compile the error is "array type has incomplete element type" Please help me
    This is my Interface
    + (void) reValueInArray: (int[][] ) labelValue replaceValue: (int) oldValue withValue: (int) newValue;
    and one more question
    How can i get length of array
    1. array that declare as array at first (int a[5] for example)
    2. array that declare as pointer at first (int a* for example)
    Thank you Very much

    Satake wrote:
    a 2 dimension array is just an array of arrays correct?
    No. It isn't.
    so it'd be something like
    - (void)arrayManipulator:(NSArray *)aTwoDimensionArray;
    You're mixing metaphors. The original poster isn't using NSArray, but, rather, C arrays.
    + (void) reValueInArray: (int[][] ) labelValue replaceValue: (int) oldValue withValue: (int) newValue;
    In C, a multi-dimensional array is just one big, single-dimensioned array that uses fixed sizes for all but one of the component arrays to find a particular element. That means that you can't ever do something like:
    There are several workarounds.
    1) Use NSArray, as suggested in the first reply. That will solve this problem and lots more. With NSArray, you really an have arrays inside of arrays.
    2) Treat the array as just a plain old pointer in the function signature, then cast it back to the properly dimensioned array.
    3) Create a true array of arrays in C, using dynamic allocation. More trouble than it's worth.
    4...N) Other options that are probably more trouble than they're worth.

  • Passing a node to Xquery function

    Hi All,
    I have two functions in my xquery. I'm trying to pass a node from one function to another function to check if it exists and do some processing on the text that is present in that node (if exists).
    declare function appendLines($node as element()) as xs:string {
         if(fn:exists($node) and $node/text() ne "") then
              fn:concat($node/text(),", ")
         else (
    appendLines($LINE_ITEM/ns0:STATXT)
    Is the above call to that function is correct?
    Thanks!!!

    declare function appendLines($node as node()*) as xs:string {
              if(fn:exists($node)) then
                   if(fn:string-length(fn:normalize-space($node/text())) > 0) then (     
                        fn:concat($node/text(), " ")
                   else (
              else (
    It worked with the above function.

  • Passing request table to Jco function

    Hello Experts,
      We have one requirement where we need to pass the table data from the BLS to SAP Jco Function Module call.  For example we are reading the material numbers from the oracle database and then we need to pass these material numbers to SAP Function Module as a table to read the further details from SAP for the given material numbers. 
      We wrote a custom function module in SAP which accepts the material number as table.  Is it possible to pass the table request parameter to Function Module?  If possible how can we do this?  I tried to pass the XML document to Function Module table, but no luck.
    Thanks
    Mohan

    Mohan,
    in the BLT, configure the JCO action to use you custom function. After pressing enter, MII reads the xml structure of the function (if the connection MII to SAP is working). In the further processing of the BLT, you can fill the RFC table which you can see in the link editor using your query results and the link editor types "AppendXML" or "AppendAfter".
    The following thread might help: [RFC call with multiple input|http://forums.sdn.sap.com/click.jspa?searchID=34070350&messageID=8134561].
    Michael

  • How to pass value in array to another procedure?

    Hello.
    I have created application by Developer form9i.
    And I have some problem about passing value in array to another procedure.
    My code is :
    PROCEDURE p_add_array (col_no in number,
    col_val in varchar2) IS     
    type xrecord is record(col number,vcol varchar2(1000));
    xrec xrecord;
    type varraytype is varying array(42) of xrecord;     
    xvartab varraytype := varraytype();
    alert number;
    BEGIN
    set_application_property(cursor_style,'busy');
    xrec.col := col_no;
    xrec.vcol := col_val;
    xvartab.extend(1);
    xvartab(col) := xrec;
    EXCEPTION
    when others then
    set_application_property(cursor_style,'default');
    alert := f_show_alert('!Error ORA-'||
    to_char(DBMS_ERROR_CODE)||' '||
    substr(DBMS_ERROR_TEXT,1,240),
    'al_stop');          
    END;
    And I want to have
    PROCEDURE p_print_arrey is
    BEGIN
    END;
    So how to bring value of xvartab( ) in p_add_array to use in p_print_array?
    Anybody please help me solve this ploblem.

    Hi,
    Instead of declaring the array locally within the procedure (i.e. p_add_array), define it in the package specification (i.e. Under Program Units).
    -- Shailender Mehta --

  • How to pass a multidimensional array to an Oracle procedure?

    How can I pass a multidimensional array to oracle array?
    Thanx in anticipation,

    Look in to passing user defined type back and forth to Oracle. Any type that oracle supports, you can constract on the java side and send it across. Look into the SQLData class.

Maybe you are looking for