本文主要附上了集合框架的简单应用代码,借鉴了一部分,然后自己整理了一点,应该够初学者受用。
代码块:
代码片段1
package cn.netjava.set;
//简单学生类定义
public class Student {
// 创建学生对象时,传入姓名和学分值
public Student(String name, int scroe) {
this.name = name;
this.scroe = scroe;
}
// 输出学生的基本信息
public void showInfo() {
System.out.println("姓名: " + name + " 学分: " + scroe);
}
// 姓名属性
private String name;
// 学分属性
private int scroe;
}
代码片段2
package cn.netjava.set;
import java.util.Set;
public class setTest {
// 程序入口
public static void main(String[] args) {
setTest test = new setTest();
java.util.Collection sSet = test.getUserSet(3);
System.out.println("集合中共有元素: " + sSet.size());
// 将Set中所有元素取出打印:
// set是无序的,所以不能根据索引取,得到set的迭带器:
java.util.Iterator<Student> it = sSet.iterator();
// 遍历:
while (it.hasNext()) {
Student st = it.next();
st.showInfo();
}
}
/**
* 取得指定数量UserInfo对象
*
* @param userCount:要创建的用户个数
* @return Set
*/
public java.util.Collection getUserSet(int userCount) {
// 创建一个集合对象
Set sSet = new java.util.HashSet();
for (int i = 0; i < userCount; i++) {
Student ui = new Student("用户_" + ((char) (65 + i)), i + 1);
sSet.add(ui);
}
return sSet;
}
}
代码片段3
package cn.netjava.set;
import java.util.ArrayList;
import java.util.List;
//List测试
public class ListTest {
//程序入口
public static void main(String[] args) {
ListTest st=new ListTest();
List<Student> list=st.getUserList(5);
System.out.println("List中共有元素: "+list.size());
//取出list中的某个位置的元素:
Student sd=list.get(3);
sd.showInfo();
//输出列表中所有Student对象信息:
st.printList(list);
}
/**
* 打印出List中对象的内容
* @param list
*/
public void printList(List<Student> list){
for(int i=0;i<list.size();i++){
//我们己知List中放的是UserInfo对象
Student us=list.get(i);;
us.showInfo();
}
}
/**
* 取得指定数量Student对象的一个List集合
* @param userCount:要创建的用户个数
* @return
*/
public java.util.List<Student> getUserList(int userCount){
List userList =new ArrayList();
for(int i=0;i<userCount;i++){
Student ui=new Student("用户_"+((char)(65+i)),i+1);
userList.add(ui);
}
return userList;
}
}
代码片段4
package cn.netjava.set;
import java.util.Map;
public class MapTest {
// 程序入口
public static void main(String[] args) {
MapTest test=new MapTest();
Map<String,Student> map=test.createUserTable();
//打印map中所有信息:
test.printMap(map);
//根据己知的key取出map中对应的一个value:
String key=""+2;
System.out.println("取出的key为"+key+"对象的信息是: ");
Student st=map.get(key);
st.showInfo();
}
/**
* 创建用户与名字关系的Map对象
* @return:用户名字与用户对象关联的Map对象
*/
public Map<String,Student> createUserTable(){
Map userMap=new java.util.HashMap();
for(int i=0;i<6;i++){
Student us=new Student("我是第"+(i+1)+"个",i);
userMap.put(""+i,us);
}
return userMap;
}
/**
* 遍历Map
* @param um:Map对象
*/
public void printMap(Map<String,Student> um){
//得到Map中所有Key的集合
java.util.Set<String> set=um.keySet();
java.util.Iterator<String> it=set.iterator();
//迭代key
while(it.hasNext()){
String key=it.next();
//取出key对应的value
Student uf=um.get(key);
uf.showInfo();
}
}
}
<!--EndFragment-->