標籤:雙向鏈表 java集合 shm hashmap 常用 generate .so hashtable 面試題
List集合有三個常用的實作類別
1.ArrayList: 底層部分使用數組實現,遍曆熟讀塊。中間插入刪除元素速度慢,線程不安全。
2. Vector: 底層部分同樣使用數組實現,線程不安全
3.LinkedList :採用雙向鏈表實現。元素的空間不連續。每個元素除了存放資料以外,還要存放上一個和下一個元素的地址。遍曆速度慢,中間插入刪除元素速度快。
List元素可以重複 Set元素不能重複 所以有的面試題會叫你去掉數組中重複的元素 可以儲存進set集合,再移出來
例如
int[] x ={1,2,3,4,5,3,3,5,2,5,7,6,9,8};
//用 set下面的Hashset方法去掉重複的
Set<Integer> set = new HashSet<Integer>();
for(int i : x){
set.add(i);
}
4 Set集合常見(底層不是數組)都在util包裡面
1.HashSet介面
輸出的序列不一定,
例如
Set<Student> set = new HashSet<Student>();
//添加
set.add(new Student(1,"張三","男"));
遍曆
因為底層不是數組,所以不能用For迴圈來遍曆
//方法一
Iterator<Student> it = set.iterator();
while(it.hasNext()){
Student s = it.next();
System.out.println(s);
}
System.out.println("=============================");
//方法二
for(Student s:set){
System.out.println(s);
}
2,TreeSet介面
可以給集合元素排序
添加刪除方法和上面一樣
用 Comparator介面 來判斷怎麼排序 需要有重寫的抽象方法 在(import java.util.Comparator;)
可以排序的set數組
Set<Student> set = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student g0, Student g1) {
return g0.getId() - g1.getId();
}
});
5,Map集合
HashMap和HashTable的區別和聯絡
1.HashMap和HashTable都是Map介面的實作類別。一個元素可以存放兩個對象。
2.HashMap允許存放空鍵和空值。而Hashtable不允許存放空鍵和空值。
3.HashMap線程不安全,而Hashtable安全執行緒
建立Map介面
Map<Integer,Student> map = new HashMap<Integer,Student>();
1.添加元素
map.put(1, new Student(1,"張三","男"));
2.根據鍵對象,尋找值對象,如果沒找到返回null
Student s = map.get(4);
3.根據鍵對象,移除元素
map.remove(2);
4.得到集合長度
System.out.println(map.size());
5.遍曆方式
1. 得到Map集合的鍵對象
Set<Integer>keySet = map.keySet();
for(Integer x : keySet){
Student st = map.get(x);
System.out.println("鍵:"+x+" 值:"+st);
}
2.Collection<Student> c = map.values();
for(Student st : c){
System.out.println(st);
}
6.演算法 分為 1.Arrays2. Collections 其中有個類 Collectios 不同於 Collction
1.Arrays
int[] array = new int[]{4,8,1,2,3,5,7,6,9};
1.對數組排序1
Arrays.sort(array);
for(int i : array){
System.out.println(i);
}
2.對數組排序2
Arrays.sort(array,new Comparator<Student>() {
@Override
public int compare(Student arg0, Student arg1) {
// TODO Auto-generated method stub
return arg0.getId() - arg1.getId();
}
});
2. Collections
List<Student> list = new ArrayList<Student>();
// 集合元素的添加
//寫進去什麼順序 出來就是什麼順序
list.add(new Student(11, "張三", 99));
list.add(new Student(8, "李四", 89));
list.add(new Student(7, "王二", 90));
list.add(new Student(9, "飛升之後", 99));
//反轉排序
Collections.reverse(list);
//亂序。隨機排列元素
Collections.shuffle(list);
//排序,需要實現Comparator比較子介面,指明定序
Collections.sort(list,new Comparator<Student>() {
@Override
public int compare(Student arg0, Student arg1) {
// TODO Auto-generated method stub
return arg0.getGrade() - arg1.getGrade();
}
});
for(Student s : list){
System.out.println(s);
}
java集合基礎