创建好友类Buddy,并设置三个属性号码,姓名,签名,并创建set、get方法。
Buddy
Buddy
public class Buddy {
private String qqId;
private String qqName;
private String impresa;
public Buddy(String qqId, String name, String impresa){
this.setImpresa(impresa);
this.setQqId(qqId);
this.setQqName(name);
}
public String getQqId() {
return qqId;
}
public void setQqId(String qqId) {
this.qqId = qqId;
}
public String getQqName() {
return qqName;
}
public void setQqName(String qqName) {
this.qqName = qqName;
}
public String getImpresa() {
return impresa;
}
public void setImpresa(String impresa) {
this.impresa = impresa;
}
}
创建组类Group,设置属性号码,名字,好友列表。
Group
Group
import java.util.ArrayList;
import java.util.List;
public class Group {
private String id;
private String groupName;
private List<Buddy> buddyList;
public Group(String id,String groupName){
this.setGroupName(groupName);
this.setId(id);
this.setBuddyList(new ArrayList<Buddy>());
}
public void addBuddy(Buddy buddy){
this.buddyList.add(buddy);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public List<Buddy> getBuddyList() {
return buddyList;
}
public void setBuddyList(List<Buddy> buddyList) {
this.buddyList = buddyList;
}
}
创建一个ArrayList,命名为gList,装载组,创建三个组g1/g2/g3,并加入到gList;创建三个Buddy,分别加入到各组;最后遍历各组,并遍历各组内的Buddy。
TestGroup
TestGroup
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class TestGroup {public static void main(String[] args) {
List<Group> gList = new ArrayList<Group>();
Group g1 = new Group("111","同学");
Group g2 = new Group("222","朋友");
Group g3 = new Group("333","同事");
gList.add(g1);
gList.add(g2);
gList.add(g3);
Buddy hans = new Buddy("01","hans","I am good");
Buddy rose = new Buddy("02","rose","I am bad");
Buddy bruce = new Buddy("03","bruce","I am man");
g1.addBuddy(hans);
g1.addBuddy(rose);
g2.addBuddy(bruce);
g3.addBuddy(hans);
Iterator<Group> git = gList.iterator();//遍历组
while(git.hasNext()){
Group p = git.next();
System.out.println("-"+p.getGroupName());
List<Buddy> bList = p.getBuddyList();
Iterator<Buddy> bit = bList.iterator();//遍历组中的好友
while(bit.hasNext()){
System.out.println(" |--"+bit.next().getQqName());
}
}
}}
结果显示:
posted on 2010-10-30 00:11
Mineralwasser 阅读(108)
评论(0) 编辑 收藏