集合
用于存放不确定数量的变量的类
- Collection
- List
- LinkedList 链表列表 插入和删除效率较高
- ArrayList 数组列表 遍历和随机访问效率较高
- Map
- HashMap
- TreeMap
- Set
- HashSet
- TreeSet
- Collections 对集合操作
泛型
使用<类型名>声明数组中要存放的类型,否则默认为Object类型
迭代器
通过iterator()方法获得该集合的迭代器
- hasNext() 是否有下一个元素
- next() 返回下一个元素
List
class Test{
public static void main(String[] args){
ArrayList<Integer> al = new ArrayList<>();
al.add(1);
al.add(2);
al.forEach(System.out::print); // 12
Iterator<Integer> it = al.iterator();
Integer i = it.next();
System.out.println(i); // 1
LinkedList<Integer> ll = new LinkedList<>();
ll.add(1);
ll.addFirst(2);
ll.forEach(System.out::print); // 21
}
}
List排序
使用list.sort()进行排序操作
被排序的对象需要实现Comparable接口,或者在sort方法中传入比较器参数
class Test{
public static void main(String []args){
List<Integer> l = new ArrayList<>();
l.add(1);
l.add(2);
l.sort(Comparator.comparing(i -> i));
l.forEach(System.out::print); // 12
l.sort(Comparator.comparing(i -> -i));
l.forEach(System.out::print); // 21
}
}
Set
Set接口存储不重复且无序的对象
- 没有get方法,通过iterator遍历
class Test{
public static void main(String[] args){
HashSet<Integer> hs = new HashSet<>();
hs.add(1);
hs.add(2);
hs.forEach(System.out::print); // 12
Iterator<Integer> it = hs.iterator();
Integer i = it.next();
System.out.println(i); // 1
}
}
Map
Map接口存储键值对
键不可重复,可以通过键获得对应的值
class Test{
public static void main(String[] args){
HashMap<Integer, String> hm = new HashMap<>();
hm.put(1, "a");
hm.put(2, "b");
hm.put(3, "c");
hm.forEach((key, val) -> System.out.print(key + "" + val)); // 1a2b3c
}
}
1254

被折叠的 条评论
为什么被折叠?



