Hi Pete,

I think the difference is there for philosophic purposes.

If you have a bean Person with attributes firstName, lastName and address, and address is of the type Address, another bean, then the code that uses that bean is supposed to: -- not be allowed to directly change the address handle (such as person.address = new Address(...)), but forced to change it only by set/get -- change the address fields (such as street and so) in the way the Address bean allows (i.e. by set/get typically)

Now, let's say the Person uses an array of Address. It is like having address0, address1, ... fields. You are not supposed to change directly them (such as address1 = new Address(...) or addresses[1] = new Address(...)) but only using the setter (setAddress1(new Address(...)) or setAddresses(1, new Address()). If getAddresses() returned the array by itself, you could then modify directly the addresses, bypassing the setter, such as getAddresses()[1]=new Address(...); <-- it changes the value in the person bean itself. Returning a clone, let you do whatever you want to the clone, still being forced to pass through the setter setAddresses(1, new Address(...)) for changing the corresponding address.

In other words, the difference comes from the fact that the array is not considered as an object member of the bean, but a shortcut for defining more than one similar members.

Hope it helps
Mihai


Pete Soper a écrit :
In the 1029 JavaBeans module in exercise 2 source file MyBeanIndedProperties.java is created and this class has the following two getters that operate with the String[] instance field "lines":

      .
      .
      String[] lines = new String[10];
      .
      .
      public String[] getLines() {
            return this.lines.clone();
      }

      public String getLines( int index ) {
            return this.lines[index];
      }

Why would getLines return a ref to a clone of the array ref'd by lines, while getLines returns a ref to the specific String in the lines array?The clone operation only clones the array object: the array elements are copies of the references, so both the orginal and cloned arrays contain the same String object references.

In other words, why wouldn't the code for getLines() be like this?

     public String[] getLines() {
         return lines;
     }

Or, alternatively, why wouldn't getLines(int) be like this?

     public String[] getLines(int index) {
         return this.lines[index].clone();
     }

Is this most likely a little inconsistency in the code, or is there something about array semantics that I'm missing that makes this difference useful?

-Pete Soper


--
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/javaprogrammingwithpassion?hl=en

Reply via email to