package cd.itcast.day1;
public class OrderItem {
private Long id;
private Double price;
private Integer num;
public OrderItem(Long id, Double price, Integer num) {
super();
this.id = id;
this.price = price;
this.num = num;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
}
package cd.itcast.day1;
/**
* 为了解决参数不固定性,引入了可变参数
*
* 类型 ... 引用名称
*
* @author Administrator
*
*/
public class VarArgsDemo {
public static void main(String[] args) {
OrderItem item1 = new OrderItem(1l, 20d, 10);
OrderItem item2 = new OrderItem(1l, 20d, 10);
OrderItem item3 = new OrderItem(1l, 20d, 10);
Double total = count(.8, new OrderItem[] { item1, item2, item3 });
System.out.println(total);
}
/**
* [Lcd.itcast.day1.OrderItem;@1fb8ee3
*
* @param items
* 1,可变参数就是数组,在编译完成之后,方法的签名变成了数组的方式 2,可变参数必须放到参数列表的最后
* @return
*/
private static Double count(Double cutoff, OrderItem... items) {
// 在1.4写法:
// Double total = new Double(0);
// Double total=Double.valueOf(0);
/**
* 这里存在大量的自动装箱/拆箱特性,这个特性也是编译器级别的特性
*/
Double total = 0d;
for (int i = 0; i < items.length; i++) {
OrderItem item = items[i];
total += item.getPrice() * item.getNum();
}
return total * cutoff;
}
private static Double sum(OrderItem[] items) {
Double total = 0d;
for (int i = 0; i < items.length; i++) {
OrderItem item = items[i];
total += item.getPrice() * item.getNum();
}
return total;
}
}
转载于:https://my.oschina.net/dendy/blog/398152