容器填充
class StringAddress { private String s; public StringAddress(String s) { this.s = s; } public String toString() { return super.toString() + " " + s; } } public class FillingLists { public static void main(String[] args) { List<StringAddress> list = new ArrayList<StringAddress>( Collections.nCopies(3, new StringAddress("Hello") ));//使用Collections包装类的nCopies()填充容器 System.out.println(list); System.out.println(); Collections.fill(list, new StringAddress("Word!")); //fill只能替换已经存在的元素,而不能添加新的元素 System.out.println(list); } }
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
运行结果:
[com.ma.array.StringAddress@61bbe9ba Hello, com.ma.array.StringAddress@61bbe9ba Hello, com.ma.array.StringAddress@61bbe9ba Hello]
[com.ma.array.StringAddress@610455d6 Word!, com.ma.array.StringAddress@610455d6 Word!, com.ma.array.StringAddress@610455d6 Word!]

更多精彩