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);

    }
}

 

运行结果:

[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!]