Java Reference
In-Depth Information
public void setPrice(double newPrice ) {
this.price = newPrice;
}
public String toString() {
return "[" + this.name + ", " + this.price + "]";
}
}
Listing 15-8 illustrates this. The main() method creates an array of Item . The array is passed to the
tryStateChange() method, which changes the price of the first element in the array to 10.38. The output shows that
the price is changed for the original element in the array created in the main() method.
Listing 15-8. Modifying the States of Array Elements of an Array Parameter Inside a Method
// ModifyArrayElementState.java
package com.jdojo.array;
public class ModifyArrayElementState {
public static void main(String[] args) {
Item[] myItems = {new Item("Pen", 25.11), new Item("Pencil", 0.10)};
System.out.println("Before method call #1:" + myItems[0]);
System.out.println("Before method call #2:" + myItems[1]);
// Call the method passing the array of Item
tryStateChange(myItems);
System.out.println("After method call #1:" + myItems[0]);
System.out.println("After method call #2:" + myItems[1]);
}
public static void tryStateChange(Item[] allItems) {
if (allItems != null && allItems.length > 0) {
// Change the price of first item to 10.38
allItems[0].setPrice(10.38);
}
}
}
Before method call #1:[Pen, 25.11]
Before method call #2:[Pencil, 0.1]
After method call #1:[Pen, 10.38]
After method call #2:[Pencil, 0.1]
the clone() method can be used to make a clone of an array. For a reference array, the clone() method
performs a shallow copy. an array should be passed to a method and returned from a method with caution. If a method
may modify its array parameter and you do not want your actual array parameter to get affected by that method call,
you must pass a deep copy of your array to that method.
Tip
 
 
Search WWH ::




Custom Search