您的位置:首页 > 编程语言 > Java开发

java-可变参数示例

2013-09-17 11:30 183 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: