1.Java中List集合的常用方法
Collections.sort(list),对List<>进行排序,类似于Arrays.sort()
list.size() 返回列表大小。
list.get(i)返回List中第i个元素,i从0到size()-1
list.remove(i)移除并且返回List中第i个元素,i从0到size()-1
list.add(i, value),在第i位置添加元素value
Collections.swap(temp,k,i),对ArrayList 的temp集合中的第k和i位交换。
2.HashMap
Map<String,char> map = new HashMap<>()
map.contiansKey(key) 返回true false,判断map里面有没有关键字key
map.put(key, c),将key键和c值进行映射
3.Collections
Java Collections类操作集合详解:
Collections 类提供了许多操作集合的静态方法,借助这些静态方法可以实现集合元素的排序、查找替换和复制等操作。
Collections 提供了如下方法用于对 List 集合元素进行排序。
void reverse(List list):对指定 List 集合元素进行逆向排序。
void shuffle(List list):对 List 集合元素进行随机排序(shuffle 方法模拟了“洗牌”动作)。
void sort(List list):根据元素的自然顺序对指定 List 集合的元素按升序进行排序。
void sort(List list, Comparator c):根据指定 Comparator 产生的顺序对 List 集合元素进行排序。
void swap(List list, int i, int j):将指定 List 集合中的 i 处元素和 j 处元素进行交换。
void rotate(List list, int distance):当 distance 为正数时,将 list 集合的后 distance 个元素“整体”移到前面;当 distance 为负数时,将 list 集合的前 distance 个元素“整体”移到后面。该方法不会改变集合的长度。
Collections.sort(temp)可以对List的temp进行排序
4.HashSet
注意对于HashSet<List< Integer >> hash,[1,2] 和[2,1]是2个不同的元素,
对于下面代码:
HashSet<List<Integer>> hash=new HashSet<List<Integer>>();
List<Integer> temp1=new ArrayList<>();
temp1.add(2);
temp1.add(1);
//List<Integer> temp1=Collections.sort(temp1);
//Collections.sort(temp1);
hash.add(temp1);
List<Integer> temp2=new ArrayList<>();
temp2.add(1);
temp2.add(2);
//Collections.sort(temp2);
hash.add(temp2);
for(List<Integer> k:hash)
System.out.println(k);
System.out.println("size:"+hash.size());
输出:
[2, 1]
[1, 2]
size:2
可以看出来[1,2] 和[2,1]是2个不同的元素。
此外HashSet都是先输出[3]再输出[6],无论是先添加temp1还是先添加temp2
可能是按照自然顺序输出的,HashSet内部按照自然顺序排列的
temp1.add(6);
temp2.add(3);
hash.add(temp1);
hash.add(temp2);
for(List<Integer> k:hash)
System.out.println(k);
temp1.add(6);
temp2.add(3);
hash.add(temp2);
hash.add(temp1);
for(List<Integer> k:hash)
System.out.println(k);
[3]
[6]
5.HashSet查找访问
HashSet不仅可以用于去重,还可以用于查找一个元素是否被访问过,这里就用带contains的API。注意用到contains的时候,最好用HashSet,不用List,因为HashSet查找效率很高,不容易超时,用List很容易超时。