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>();
a.add("a"); a.add("b"); a.add("c"); a.add(1, "d");
boolean b=a.contains("f");
String s1=a.get(1); String s2=a.get(5);
int i=a.indexOf("a");
a.remove("a"); a.remove(1);
a.set(1,"aaa");
int si=a.size();
ArrayList<String> a1=new ArrayList<String>(); a1.add("e"); a1.add("f"); a.addAll(a1);
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<String> q= new LinkedList<String>();
q.offer("aa");
String s1 = q.poll();
String s2 = q.peek()
|
Stack
1 2 3 4 5 6 7 8 9 10 11
| Object peek( )
Object pop( )
Object push(Object element)
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( )
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<>();
Comparator<Student> comp = new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { if(s1.score1>=s2.score1) return 1; else return -1; } }; Collections.sort(slist, comp);
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);
|