java集合框架:
1.集合概念:集合可以看做是我們在內存中存放一組對象的容器,就像數組,或隊列一樣,
2.java.util.Set接口 他的子類類提供的是一個無序的集合;
java.util.List接口 他的子類提供的是一個有序的集合;
java.util.Map接口 他提供了一個映射關係的集合數據結構;
3.List接口
如:創建一個裝學生對象的List
public List<Student> createList(){
//構造學生隊列 ,並將隊列長度固定爲 20
List<Student> list = new ArrayList<Student>(20);
//用循環將創建對象並將其添加到隊列中
for(int i=0;i<20;i++){
//設置參數
String name = "學生"+((char)(65+i));
Random rand = new Random();
int score = rand.nextInt(20);
//設置學生信息
Student stu = new Student(name,score);
list.add(stu);
}
return list;
}
這樣就創建了一個裝存學生對象的List集合,並用隨機數給他賦了值。
public void deleteScore(List<Student> list,int score){
System.out.println("刪除的學生爲:");
//用循環開始尋找
for(int i=0;i<list.size();){
//獲取每個學生的對象
Student stu = list.get(i);
//匹配
if(stu.getScore() < score){
System.out.println(stu.getName()+": "+stu.getScore());
list.remove(stu);
}
else{
i++;
}
}
}
這樣就刪除了小於Score分數的學生,需要注意的是,每當你刪除一個學生,List的長度就會減少一個單位,
所以在用循環的時候,要注意控制循環變量的變化!!
4.Set集合
Set集合的創建和List的差不多,因爲他們的add函數都一樣
如:
public Set<Student> createList(){
//構造學生隊列 ,並將隊列長度固定爲 20
Set<Student> set = new HashSet<Student>(20);
//用循環將創建對象並將其添加到隊列中
for(int i=0;i<20;i++){
//設置參數
String name = "學生"+((char)(65+i));
Random rand = new Random();
int score = rand.nextInt(20);
//設置學生信息
Student stu = new Student(name,score);
set.add(stu);
}
return set;
}
這個就可以不用說了,值得一提的是,在Set中,需要尋找到某一個數據時,不能用get函數,因爲Set根本沒
有Get函數,我們需要用到迭代器!!
如:
public void searchScore(Set<Student> set,int score){
System.out.println("成績爲"+score+"的學生有:");
//獲取迭代器
Iterator<Student> ite = set.iterator();
//循環找,並打印
while(ite.hasNext()){
//獲取相應位置上的學生對象
Student stu = ite.next();
if(score == stu.getScore())
System.out.println(stu.getName()+": "+stu.getScore());
}
}
這裏有兩個非常重要的函數 hasNext(),判斷set是否有後繼,next()即爲返回他的後繼。還有在刪除的時候
必須要用數組存儲起來一次性刪除,
Set<Student> s = new HashSet<Student>();
Student stu = ite.next();
if(score >stu.getScore()){
s.add(stu);
System.out.println(stu.getName()+": "+stu.getScore());
}
然後就remove(s);就ok啦
Map,Map是一個特殊的集合,他沒有父類,他由映射關係形成,key值不可重複,而影射值是可以重複的,他
的一些使用方法與其他兩種大致相同,不同的是,尋找他的數據需要嗎,利用key值建造set的集合接口,然
後用set的迭代器根據key值映射尋找自己的值:
如:
public void searchScore(Map<Integer,Student> map,int score){
System.out.println("成績爲"+score+"的學生有:");
//創建set集合框架
Set<Integer> set = map.keySet();
//獲取迭代器 (Set中只有這樣才能獲取下一個對象,因爲他是無序不重複的)
Iterator<Integer> ite = set.iterator();
//創建隊列將要刪除的東西保存到隊列
Set<Student> s = new HashSet<Student>();
while(ite.hasNext()){
//獲取相應位置上的學生對象
int number = ite.next();
Student stu = map.get(number);
if(score >stu.getScore()){
s.add(stu);
System.out.println(stu.getName()+": "+stu.getScore());
}
}
}
裏邊多了個函數keySet(),是把map的key轉化爲set集合類型。map的刪除和set裏得差不多,還是把key用set裝起來,利用set的迭代器來尋找key值,然後利用key值找到數據,把數據存起來,刪除就ok。
代碼就不寫了,相信好好看了前面的童鞋都應該能想到。
多多指教