Java - Array with Object Elements

Introduction

If the array's reference type is mutable, you can change the state of the object stored in the array elements.

The following code changes the state of the object referred to by the elements of the array.

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 1.3.

The output shows that the price is changed for the original element in the array created in the main() method.

Demo

class Item {
  private double price;
  private String name;

  public Item(String name, double initialPrice) {
    this.name = name;
    this.price = initialPrice;
  }//from ww  w . ja v  a  2s  .c o m

  public double getPrice() {
    return this.price;
  }

  public void setPrice(double newPrice) {
    this.price = newPrice;
  }

  public String toString() {
    return "[" + this.name + ", " + this.price + "]";
  }
}

public class Main {
  public static void main(String[] args) {
    Item[] myItems = { new Item("Pen", 2.11), new Item("Pencil", 0.10) };
    System.out.println("Before method call #1:" + myItems[0]);
    System.out.println("Before method call #2:" + myItems[1]);

    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) {
      allItems[0].setPrice(1.3);
    }
  }
}

Result