看到一篇非常好的文章,不是非常理解,写一博客权当记录。
数组转成List,参考
Collections 比数组好,与数组相比arrays具有性能优势,例如,若要将数组的内容转储到一个字符串,需要迭代整个数组,然后将内容连接成一个 String;而 Collections 的实现都有一个可用的 toString() 实现。
person类
package com.zz.bridge;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Person implements Iterable<Person>{
private String firstName;
private String lastName;
private int age;
private List<Person> children = new ArrayList<Person>();
//可变长参数,就是这个位置可以传入 0~任意个该类型参数
public Person(String fn, String ln, int a, Person... kids){
this.firstName = fn;
this.lastName = ln;
this.age = a;
for (Person child : kids)
children.add(child);
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
public int getAge() {
return this.age;
}
public Iterator<Person> iterator() {
return children.iterator();
}
public void setFirstName(String value) {
this.firstName = value;
}
public void setLastName(String value) {
this.lastName = value;
}
public void setAge(int value) {
this.age = value;
}
public String toString() {
return "[Person: " +
"firstName=" + firstName + " " +
"lastName=" + lastName + " " +
"age=" + age + "]";
}
}
main类
package com.zz.bridge.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.zz.bridge.Person;
public class BridgeTest
{
public static void main(String[] args)
{
//生成一个对象,这个对象中包含两个子节点
Person ted = new Person("Ted", "Neward", 39,
new Person("Michael", "Neward", 16),
new Person("Matthew", "Neward", 10));
System.out.println(ted);
//遍历孩子节点
for (Person kid : ted)
{
System.out.println(kid.getFirstName()+kid.toString());
}
}
}