Java基础梳理:数组(9)

Java基础梳理:数组

简单应用

  假设一个ATM机器里有六个钱箱,每个钱箱存放不同的面值,那么我们该如何初始化这些钱箱呢?一般情况下我们会这么做

1 public class CashUnit { 2 private int value; 3 4 public int getValue() { 5 return value; 6 } 7 8 public void setValue(int value) { 9 this.value = value; 10 } 11 12 public int getCount() { 13 return count; 14 } 15 16 public void setCount(int count) { 17 this.count = count; 18 } 19 20 private int count; 21 }

 

View Code

 

1 CashUnit[] cashUnit=new CashUnit[6]; 2 cashUnit[0].setValue(100); 3 cashUnit[1].setValue(50); 4 cashUnit[2].setValue(20); 5 cashUnit[3].setValue(10); 6 cashUnit[4].setValue(5); 7 cashUnit[5].setValue(1);

  我么还可以通过索引对应值的方式去实现

1 public static int[] cashValues = { 100, 50, 20, 10, 5, 1 }; 2 3 public static CashUnit[] createCashUnits() { 4 CashUnit[] cashUnit = new CashUnit[6]; 5 for (int i = 0; i < cashUnit.length; i++) { 6 cashUnit[i].setValue(cashValues[i]); 7 } 8 return cashUnit; 9 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/fd09c906fe5caa20117b5b91c93c3d34.html