JAVA學習筆記——集合
一、Collection接口
1.List(有序可重複)序列
ArrayList
數組序列
(1).add()插入元素
1.依次按照順序向ArrayList中添加數據
用法:
將a添加到list中
list.add("a");
2.在第N個位置添加一個數據
用法:
在第1個位置添加E
list.add(1, "E");
注意:1.如果x位置上已經有元素則會取代原有元素的位置,原有元素會後移
2.ArrayList中必須有足夠多的數據,例如ArrayList中沒有任何數據,這個時候使用arraylist.add(1, "E");就會出現java.lang.IndexOutOfBoundsException異常。
Course cr1=new Course("1","數據結構");
coursesToSelect.add(cr1);//依次向List裏添加數據
(2)get()獲取該位置元素
Course temp= (Course) coursesToSelect.get(0);//temp=第0個元素
Course cr2=new Course("2","C語言");
coursesToSelect.add(1,cr2);//在第1個位置添加cr2,如果第x個位置有元素就自動後移在x+1的位置添加,get與index值一致
(3).iterator()迭代器
/*
*利用迭代器輸出List
*/
public void testIterator(){
Iterator it=coursesToSelect.iterator();
System.out.println("有以下課程待選(迭代器訪問)");
while (it.hasNext()){
Course cr= (Course) it.next();
System.out.println("課程序號:"+cr.id+";課程名稱:"+cr.name);
}
}
(4).set修改內容
public void testModify(){
coursesToSelect.set(4,new Course("4","毛概"));
}
(5)contains方法判斷是否存在該元素
原理:係統會對list中的每個元素e調用o.equals(e),方法,加入list中有n個元素,那麼會調用n次o.equals(e),隻要有一次o.equals(e)返回了true,那麼list.contains(o)返回true,否則返回false。
public void testListCoures(){
Course course= (Course) coursesToSelect.get(0);
System.out.println("取得備選課程"+course.name);
System.out.println("List是否存在備選課程"+coursesToSelect.contains(course));
}
contains方法調用equals()方法實現比較,如果需要比較List中是否存在某個值,則需要重寫equals()方法
@Override
public boolean equals(Object obj) {
if (this == obj) //比較兩個obj的值是否相等
return true;
if (obj == null) //如果obj值為空
return false;
if (!(obj instanceof Course)) //obj是否為Course的實例
return false;
Course other = (Course) obj; //創建實例other賦值obj
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
(6)indexOf()方法返回索引位置
注:如果一個List中存在多個相同值,則IndexOf()返回第一個值的索引位置,
lastIndexOf()則返回最後一個值的索引位置。
LinkedList
2.Queue(有序可重複)隊列
3.Set(無序不可重複)集
HashSet
Set中,添加某個對象,無論添加多少次, 最終隻會保留一個該對象(的引用), 並且,保留的是第一次添加的那一個
for (Course cr : st.coursesToSelect) {
if (cr.id.equals(courseid)) {
student.courses.add(cr);
/**
* Set中,添加某個對象,無論添加多少次, 最終隻會保留一個該對象(的引用), 並且,保留的是第一次添加的那一個
*/
student.courses.add(null);//set可以添加null值
student.courses.add(cr);
}
}
二、Map接口
HashMap實現類
<key,value>
三、collections工具類
用來操作集合對象的工具類
1.sort()排序
public void sort1(){
List<Integer> integerList=new ArrayList<Integer>();
Random random=new Random();
Integer t;
for (int i=0;i<10;i++){
do {
t=random.nextInt(100);//向List中添加10個100以內的整數
}while (integerList.contains(t));
integerList.add(t);
System.out.println("成功添加"+t);
}
System.out.println("———————————排序前———————————");
for (Integer integer:integerList
) {
System.out.println("元素"+integer);
}
System.out.println("———————————排序後———————————");
//******************************************
//調用Collections的sort方法對integerList進行排序
Collections.sort(integerList);
for (Integer integer:integerList
) {
System.out.println("元素"+integer);
}
}
參考資料:
1、Java第三季 作者:陳碼農
2、Java 增強型的for循環 for each 作者:聖騎士Wind
3、List的contains()方法 作者:CMTobby
最後更新:2017-07-25 18:32:48