0%

java集合框架常用知识点总结

ArrayList

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
ArrayList<String> a=new ArrayList<String>();

//add()函数
a.add("a"); //[a]
a.add("b"); //[a, b]
a.add("c"); //[a, b, c]
a.add(1, "d"); //[a, d, b, c]

//contains()
boolean b=a.contains("f"); //false

//get()
String s1=a.get(1); //d
String s2=a.get(5); //运行时抛出IndexOutOfBoundsException

//indexOf()
int i=a.indexOf("a"); //0

//remove()
a.remove("a"); //[d, b, c]
a.remove(1); //[d, c]

//set()
a.set(1,"aaa"); //[d, aaa]

//size()
int si=a.size(); //2

//addAll()
ArrayList<String> a1=new ArrayList<String>();
a1.add("e");
a1.add("f");
a.addAll(a1); //[d, aaa, e, f]

//clear()
a.clear(); //[]

//遍历
for(String s:a){
System.out.println(s);
}


LinkedList

基本上ArrayList函数都适用于LinkedList。LinkedList还可以使用如下函数:

1
2
3
4
5
6
7
8
void addFirst(Object element)
void addLast(Object element)

Object getFirst()
Object getLast()

Object removeFirst()
Object removeLast()


Queue

1
2
3
4
5
6
7
8
9
10
11
//Queue代表FIFO 先进先出的队列
Queue<String> q= new LinkedList<String>();

//offer() 加在队列的最后面
q.offer("aa");

//poll() 取出并返回第一个。如果队列为空,返回null
String s1 = q.poll();

//peek() 查看第一个,但是不取出来。如果队列为空,返回null
String s2 = q.peek()


Stack

1
2
3
4
5
6
7
8
9
10
11
//查看stack顶部的元素
Object peek( )

//取出并返回stack顶部元素
Object pop( )

//加在stack顶部
Object push(Object element)

//判断stack是否为空
boolean empty()


HashMap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
HashMap<String,String> m = new HashMap<>();
m.put("name", "Tony");
m.put("address", "Guangzhou");


Object get(Object key)

Object remove(Object key)

void clear( )

int size( )

//遍历map
for (Map.Entry<String, String> entry : m.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}


Collections常用函数

1
2
3
4
5
6
7
8
9
10
11

List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 10; i++) {
numbers.add(i);
}

Collections.reverse(numbers);

Collections.sort(numbers);

Collections.swap(numbers,0,5);


Comparator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class Student{
public int score1;
public int score2;
}

List<Person> slist = new ArrayList<>();

//直接使用Collections.sort(slist)会编译出错
//需引入Comparator,指定比较的算法, 这里按score1由低到高排序
Comparator<Student> comp = new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
//按照score1进行排序
if(s1.score1>=s2.score1)
return 1; //正数表示h1比h2要大
else
return -1;
}
};
Collections.sort(slist, comp);

//或者Student类实现Comparable接口,在类里面提供比较的算法
public class Student implements Comparable<Student>{
public int score1;
public int score2;
@Override
public int compareTo(Hero h){
if(score1>=h.score1)
return 1;
else
return -1;
}
}
Collections.sort(slist);