目录
List集合的实现类 ArrayList、LinkedList
-
集合
集合类的特点: 提供一种存储空间可变的存储模型,存储的数据容量可以随时发生改变
集合类的体系图
-
Collection集合
Collection集合的常用方法
方法名 | 说明 |
boolean add(E e) | 添加元素 |
boolean remove(Object o) | 从集合中移除指定的元素 |
void clear() | 清空集合中的元素 |
boolean contains(Object o) | 判断集合中是否存在指定的元素 |
boolean isEmpty() | 判断集合是否为空 |
int size() | 集合的长度,也就是集合中元素的个数 |
Collection集合的遍历
迭代器概述:迭代器,集合的专用遍历方式
-
List集合
List集合概述和特点:
List集合的特有方法
方法名 | 描述 |
void add(int index,E element) | 在此集合中的指定位置插入指定的元素 |
E remove(int index) | 删除指定索引处的元素,返回被删除的元素 |
E set(int index,E element) | 修改指定索引处的元素,返回被修改的元素 |
E get(int index) | 返回指定索引处的元素 |
遍历方式:迭代器,for循环
-
并发修改异常
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("java");
list.add("world");
Iterator<String> iterator = list.iterator();
//在使用迭代器的时候,每次next都会判断list修改次数和预期修改次数是否一致,
//在使用迭代器遍历的时候,添加元素会导致此异常
/*while(iterator.hasNext()){
String next = iterator.next();
if(next.equals("java")){ //java.util.ConcurrentModificationException
list.add("晚安");
}
}*/
for(int i=0; i<list.size(); i++){
String s = list.get(i);
if(s.equals("java")){
list.add("晚安");
}
}
System.out.println(list);
}
-
listIterator和iterator的区别
listIterator 继承 iterator,iterator有的功能 listIterator 都有
listIterator | iterator | |
在迭代期间修改列表 | 可以 | 不行:并发修改异常 |
任意方向遍历 | 可以 | 只能向下遍历 |
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("java");
list.add("world");
Iterator<String> iterator = list.iterator();
ListIterator<String> listIterator = list.listIterator();
//在使用迭代器的时候,每次next都会判断list修改次数和预期修改次数是否一致,
//在使用迭代器遍历的时候,添加元素会导致此异常
/*while(iterator.hasNext()){
String next = iterator.next();
if(next.equals("java")){ //java.util.ConcurrentModificationException
list.add("晚安");
}
}*/
while(listIterator.hasNext()) {
//String next = listIterator.previous();
String next = listIterator.next(); //逆向遍历(从后到前)
if (next.equals("java")) {
listIterator.add("晚安"); //使用 listIterator自带的 add方法添加元素
//该add方法将列表实际修改次数赋值给预期修改次数
}
}
/* for(int i=0; i<list.size(); i++){
String s = list.get(i);
if(s.equals("java")){
list.add("晚安");
}
}*/
System.out.println(list);
}
//--------------------result---------------------------
[hello, java, 晚安, world]
-
增强for循环
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("java");
list.add("world");
for(String str: list){
System.out.println(str);
}
//增强for语句内部实际是一个Iterator,验证如下
for(String str: list){
if(str.equals("java")){
list.add("晚安"); //报错:ConcurrentModificationException
}
}
System.out.println(list);
}
//------------------result---------------------
hello
Exception in thread "main" java
world
java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1042)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:996)
at com.Test.Test.main(Test.java:17)
-
数据结构
数据结构之栈和队列
- 栈结构先进后出
- 队列结构先进先出
数据结构之数组和链表
- 数组结构:查询快、增删慢
- 队列结构:查询慢、增删快
-
List集合的实现类 ArrayList、LinkedList
- ArrayList集合:底层是数组结构实现,查询快、增删慢
- LinkedList集合:底层是链表结构实现,查询慢、增删快
-
LinkedList
LinkedList集合的特有功能
方法名 | 说明 |
public void addFirst(E e) | 在该列表开头插入指定的元素 |
public void addLast(E e) | 将指定的元素追加到此列表的末尾 |
public E getFirst() | 返回此列表中的第一个元素 |
public E getLast() | 返回此列表中的最后一个元素 |
public E removeFirst() | 从此列表中删除并返回第一个元素 |
public E removeLast() | 从此列表中删除并返回最后一个元素 |
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("hello");
list.add("world");
list.add("java");
list.addLast("晚安"); // addLast 等价于 add
list.addFirst("head");
System.out.println(list);
//中间添加元素
list.add(2,"asdqwe");
/* public void add(int index, E element) {
this.checkPositionIndex(index);
if (index == this.size) {
this.linkLast(element);
} else {
this.linkBefore(element, this.node(index));
}
}*/
/* LinkedList.Node<E> pred = succ.prev;
LinkedList.Node<E> newNode = new LinkedList.Node(pred, e, succ);
succ.prev = newNode;
if (pred == null) {
this.first = newNode;
} else {
pred.next = newNode;
}*/
System.out.println(list);
}
-
Set集合
Set集合概述和特点
特点:
1.set集合是不包含重复元素的集合
2.没有带索引的方法,所以不能使用普通for循环遍历
public static void main(String[] args) {
Set<String> set = new HashSet<String>(); //HashSet是无序的,是Set的实现类
set.add("hello");
set.add("java");
set.add("world");
System.out.println(set);
//不包含重复元素
set.add("world");
System.out.println(set);
for(String str: set){
System.out.println(str);
}
System.out.println("--------------------");
Iterator<String> iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
//--------------result---------------
[java, world, hello]
[java, world, hello]
java
world
hello
--------------------
java
world
hello
-
哈希值
哈希值简介:是JDK根据对象的地址或者字符串或者数字算出来的int类型的数值
如何获取哈希值:Object类中的public int hashCode():返回对象的哈希码值
System.out.println("李淳风".hashCode()); //26326281
System.out.println("袁天罡".hashCode()); //34322329
System.out.println("----------------------------");
//String类重写了hashCode()方法,可以使某些字符串的hash值相同
System.out.println("重地".hashCode()); //1179395
System.out.println("通话".hashCode()); //1179395
System.out.println("----------------------------");
Student student1 = new Student("李淳风", 25, "男");
Student student2 = new Student("袁天罡", 30, "男");
System.out.println(student1.hashCode()); //381259350
System.out.println(student2.hashCode()); //2129789493
System.out.println("----------------------------");
System.out.println(student1.hashCode()); //381259350
student1.setName("李嗣源");
System.out.println(student1.hashCode()); //381259350
26326281
34322329
----------------------------
1179395
1179395
----------------------------
381259350
2129789493
----------------------------
381259350
381259350
-
HashSet集合概述和特点
public static void main(String[] args) {
HashSet<String> hashSet = new HashSet<>();
hashSet.add("java");
hashSet.add("java");
System.out.println(hashSet);
/* public boolean add(E e) {
return this.map.put(e, PRESENT) == null;
}
static final int hash(Object key) {
int h;
return key == null ? 0 : (h = key.hashCode()) ^ h >>> 16;
}
public V put(K key, V value) {
return this.putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
HashMap.Node[] tab;
int n;
//如果哈希表为初始化,就对其进行初始化
if ((tab = this.table) == null || (n = tab.length) == 0) {
n = (tab = this.resize()).length;
}
Object p;
int i;
//根据对象的hash值计算对象的存储位置。如果该位置没有元素,就存储元素
if ((p = tab[i = n - 1 & hash]) == null) {
tab[i] = this.newNode(hash, key, value, (HashMap.Node)null);
} else {
Object e;
Object k;
//根据对象的hash值计算对象的存储位置。如果该位置有元素,就比较哈希值
//如果哈希值不同,会继续向下执行把元素添加到集合
//如果哈希值相同,会调用对象的equals方法
//如果返回true,说明元素重复不存储
//如果返回false,会继续向下执行,把元素添加到集合
if (((HashMap.Node)p).hash == hash && ((k = ((HashMap.Node)p).key) == key || key != null && key.equals(k))) {
e = p;
} else if (p instanceof HashMap.TreeNode) {
e = ((HashMap.TreeNode)p).putTreeVal(this, tab, hash, key, value);
} else {
int binCount = 0;
while(true) {
if ((e = ((HashMap.Node)p).next) == null) {
((HashMap.Node)p).next = this.newNode(hash, key, value, (HashMap.Node)null);
if (binCount >= 7) {
this.treeifyBin(tab, hash);
}
break;
}
if (((HashMap.Node)e).hash == hash && ((k = ((HashMap.Node)e).key) == key || key != null && key.equals(k))) {
break;
}
p = e;
++binCount;
}
}
if (e != null) {
V oldValue = ((HashMap.Node)e).value;
if (!onlyIfAbsent || oldValue == null) {
((HashMap.Node)e).value = value;
}
this.afterNodeAccess((HashMap.Node)e);
return oldValue;
}
}
++this.modCount;
if (++this.size > this.threshold) {
this.resize();
}
this.afterNodeInsertion(evict);
return null;
}*/
}
-
常见数据结构之哈希表
-
HashSet集合存储学生对象并遍历【应用】
-
LinkedHashSet集合概述和特点
/*
LinkedHashSet集合特点
1:哈希表和链表实现的Set接口,具有可预测的迭代次序
2:由链表保证元素有序,也就是说元素的存储和取出顺序是一致的
3:由哈希表保证元素唯一,也就是说没有重复的元素
*/
//创建集合对象
LinkedHashSet<String> linkedSet = new LinkedHashSet<>();
linkedSet.add("java");
linkedSet.add("world");
linkedSet.add("hello");
linkedSet.add("java");
System.out.println(linkedSet); //[java, world, hello]
-
TreeSet集合概述和特点
public static void main(String[] args) {
/*
LinkedHashSet集合特点
1:哈希表和链表实现的Set接口,具有可预测的迭代次序
2:由链表保证元素有序,也就是说元素的存储和取出顺序是一致的
3:由哈希表保证元素唯一,也就是说没有重复的元素
*/
TreeSet<Integer> treeSet = new TreeSet<>();
//添加元素
treeSet.add(5); //自动装箱(将int类型转为Integer类型)
treeSet.add(9);
treeSet.add(3);
treeSet.add(7);
treeSet.add(6);
System.out.println(treeSet); //[3, 5, 6, 7, 9]
/*//增强for循环遍历集合
for(Integer i: treeSet){
System.out.println(i);
}*/
}
自然排序Comparable的使用
public static void main(String[] args) {
TreeSet<Student> treeSet = new TreeSet<>();
treeSet.add(new Student("李淳风", 25));
treeSet.add(new Student("袁天罡", 50));
treeSet.add(new Student("李茂贞", 30));
treeSet.add(new Student("李克用", 50));
treeSet.add(new Student("李克用", 50)); //重复对象不会再添加
for(Student stu: treeSet){
System.out.println("["+stu.getName()+", "+ stu.getAge() + "]");
}
}
//---------------------result--------------------
[李淳风, 25]
[李茂贞, 30]
[李克用, 50]
[袁天罡, 50]
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student s) {
// return 0; //返回相同,默认每次传入对象相同
// return 1; //升序
// return -1; //降序
//按照年龄从小到大排序
int num = this.age - s.age; //按照年龄从小到大排序
// int num = s.age - this.age; //按照年龄从大到小排序
//年龄相同时,按照姓名的字母顺序排序
int num2 = num==0?this.name.compareTo(s.name):num;
return num2;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public static void main(String[] args) {
TreeSet<Student> treeSet = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student stu1, Student stu2) {
// return 0; //返回相同,默认每次传入对象相同
// return 1; //升序
// return -1; //降序
//按照年龄从小到大排序
int num = stu1.getAge() - stu2.getAge(); //按照年龄从小到大排序
// int num = s.age - this.age; //按照年龄从大到小排序
//年龄相同时,按照姓名的字母顺序排序
int num2 = num==0?stu1.getName().compareTo(stu2.getName()):num;
return num2;
}
});
treeSet.add(new Student("李淳风", 25));
treeSet.add(new Student("袁天罡", 50));
treeSet.add(new Student("李茂贞", 30));
treeSet.add(new Student("李克用", 50));
treeSet.add(new Student("李克用", 50)); //重复对象不会再添加
for(Student stu: treeSet){
System.out.println("["+stu.getName()+", "+ stu.getAge() + "]");
}
}
//---------------------result---------------------
[李淳风, 25]
[李茂贞, 30]
[李克用, 50]
[袁天罡, 50]
public class Student{
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
-
泛型
泛型概述和好处
- 泛型类
public static void main(String[] args) {
Student<String> stuStr = new Student<>();
Student<Integer> stuInt = new Student<>();
stuStr.setName("李茂贞");
stuInt.setAge(25);
System.out.println(stuStr.getName()); //李茂贞
System.out.println(stuInt.getAge()); //25
}
public class Student<T>{
private T name;
private T age;
public Student() {
}
public Student(T name, T age) {
this.name = name;
this.age = age;
}
public T getName() {
return name;
}
public void setName(T name) {
this.name = name;
}
public T getAge() {
return age;
}
public void setAge(T age) {
this.age = age;
}
}
- 泛型方法
格式: 修饰符 <泛型> void 方法名(){ }
public static void main(String[] args) throws ParseException {
GenericImpl generic = new GenericImpl();
generic.show("李茂贞");
generic.show(25);
generic.show(25.1);
generic.show(false);
}
public class GenericImpl {
public <T> void show(T t) {
System.out.println(t);
}
}
//-----------------result-----------------
李茂贞
25
25.1
false
public static void main(String[] args) throws ParseException {
show("李茂贞");
show(25);
show(29.1);
show(true);
show('s');
}
//泛型方法
public static <T> void show(T t){
System.out.println(t);
}
//-------------result---------------
李茂贞
25
29.1
true
s
- 泛型接口
public static void main(String[] args) throws ParseException {
Generic<String> genericStr = new GenericImpl<String>();
genericStr.show("李茂贞"); //李茂贞
Generic<Integer> genericInt = new GenericImpl<Integer>();
genericInt.show(25); //25
}
public interface Generic<T> {
<T> void show(T t);
}
public class GenericImpl<T> implements Generic<T> {
@Override
public <T> void show(T t) {
System.out.println(t);
}
}
-
类型通配符
/*
类型通配符:<?>
List<?>:表示元素类型未知的List,它的元素可以匹配任何的类型
这种带通配符的List仅表示它是各种泛型List的父类,并不能把元素添加到其中
类型通配符上限:<? extends 类型>
List<? extends Number>:它表示的类型是Number或者其子类型
类型通配符下限:<? super 类型>
List<? super Number>:它表示的类型是Number或者其父类型
*/
public class GenericDemo {
public static void main(String[] args) {
//类型通配符:<?>
List<?> list1 = new ArrayList<Object>();
List<?> list2 = new ArrayList<Number>();
List<?> list3 = new ArrayList<Integer>();
System.out.println("--------");
//类型通配符上限:<? extends 类型>
// List<? extends Number> list4 = new ArrayList<Object>();
List<? extends Number> list5 = new ArrayList<Number>();
List<? extends Number> list6 = new ArrayList<Integer>();
System.out.println("--------");
//类型通配符下限:<? super 类型>
List<? super Number> list7 = new ArrayList<Object>();
List<? super Number> list8 = new ArrayList<Number>();
// List<? super Number> list9 = new ArrayList<Integer>();
}
}
-
可变参数
public static void main(String[] args) throws ParseException {
System.out.println(sum(1,2));
System.out.println(sum(1,2,3));
System.out.println(sum(1,2,3,4));
System.out.println(sum(1,2,3,4,5));
System.out.println(sum(1,2,3,4,5,6,78,9));
}
public static int sum(int... a){
int result = 0;
for(int i: a){
result += i;
}
return result;
}
//可变参数放最后
//public static int sum(int... a, int b){ //报错
public static int sum1(int b, int... a){
int result = 0;
for(int i: a){
result += i;
}
return result;
}
//-----------------result-------------------
3
6
10
15
108
可变参数的使用
//public static <T> List<T> asList(T... a):返回由指定数组支持的固定大小的列表
// List<String> list = Arrays.asList("hello", "world", "java");
//
list.add("javaee"); //UnsupportedOperationException
list.remove("world"); //UnsupportedOperationException
// list.set(1,"javaee");
//
// System.out.println(list);
//public static <E> List<E> of(E... elements):返回包含任意数量元素的不可变列表
// List<String> list = List.of("hello", "world", "java", "world");
//
list.add("javaee");//UnsupportedOperationException
list.remove("java");//UnsupportedOperationException
list.set(1,"javaee");//UnsupportedOperationException
//
// System.out.println(list);
//public static <E> Set<E> of(E... elements) :返回一个包含任意数量元素的不可变集合
// Set<String> set = Set.of("hello", "world", "java","world"); //set集合不允许重复的元素 IllegalArgumentException
Set<String> set = Set.of("hello", "world", "java");
// set.add("javaee");//UnsupportedOperationException
// set.remove("world");//UnsupportedOperationException
System.out.println(set);
-
Map集合
Map<String, String> map = new HashMap<>();
map.put("001", "袁天罡");
map.put("002", "李茂贞");
map.put("003", "李嗣源");
//当key已经存在,put方法将覆盖之前的值
map.put("003", "李克用");
System.out.println(map);
Map集合的基本功能
方法名 | 说明 |
V put(K key,V value) | 添加元素 |
V remove(Object key) | 根据键删除键值对元素 |
void clear() | 移除所有的键值对元素 |
boolean containsKey(Object key) | 判断集合是否包含指定的键 |
boolean containsValue(Object value) | 判断集合是否包含指定的值 |
boolean isEmpty() | 判断集合是否为空 |
int size() | 集合的长度,也就是集合中键值对的个数 |
Map<String, String> map = new HashMap<>();
map.put("001", "袁天罡");
map.put("002", "李茂贞");
map.put("003", "李克用");
map.put("004", "李嗣源");
System.out.println(map.remove("004")); //李嗣源,remove返回值为被删除的键值对的值
System.out.println(map.remove("005")); //null,当被删除的键值对的键不存在时,返回值为null
System.out.println(map.containsKey("001")); //true
System.out.println(map.containsKey("005")); //false
System.out.println(map.containsValue("李茂贞")); //true
System.out.println(map.containsValue("李淳风")); //false
//map.clear(); //删除所有的键值对
//判断稽核是否为空
System.out.println(map.isEmpty()); //false
//获取集合的长度
System.out.println(map.size()); //3
System.out.println(map);
Map集合的获取功能
方法名 | 说明 |
V get(Object key) | 根据键获取值 |
Set keySet() | 获取所有键的集合 |
Collection values() | 获取所有值的集合 |
Set<Map.Entry<K,V>> entrySet() | 获取所有键值对对象的集合 |
Map<String, String> map = new HashMap<>();
map.put("001", "袁天罡");
map.put("002", "李茂贞");
map.put("003", "李星云");
map.put("005", "李淳风");
System.out.println(map.get("005")); //李淳风
System.out.println(map.get("009")); //null,键不存在时返回值为null
//获取所有键的集合
Set<String> keySet = map.keySet();
System.out.println(keySet); //[001, 002, 003, 005]
//获取所有值的集合
Collection<String> values = map.values();
System.out.println(values); //[袁天罡, 李茂贞, 李星云, 李淳风]
//---------------------result--------------------------
李淳风
null
[001, 002, 003, 005]
[袁天罡, 李茂贞, 李星云, 李淳风]
map集合的遍历
Map<String, String> map = new HashMap<>();
map.put("001", "袁天罡");
map.put("002", "李茂贞");
map.put("003", "李星云");
map.put("005", "李淳风");
//map集合的遍历
//方式一
Set<String> keySet = map.keySet(); //获取所有key的Set集合
for(String key: keySet){
String value = map.get(key);
System.out.print(key + "=" + value +", ");
}
System.out.println();
//方式二
Set<Map.Entry<String, String>> entrySet = map.entrySet();//获取所有键值对对象的集合
for(Map.Entry<String, String> keyValue: entrySet){
String key = keyValue.getKey();
String value = keyValue.getValue();
System.out.print(key + "=" + value +", ");
}
001=袁天罡, 002=李茂贞, 003=李星云, 005=李淳风,
001=袁天罡, 002=李茂贞, 003=李星云, 005=李淳风,
-
HashMap集合练习之键是Student值是String
Map<Student, String> map = new HashMap<>();
map.put(new Student("李淳风", 25), "北京");
map.put(new Student("袁天罡", 30), "上海");
map.put(new Student("李茂贞", 26), "深圳");
Student stu1 = new Student("尤川", 26);
Student stu2 = new Student("尤川", 26);
//需要重写hashCode,equals方法,才能将Student键去重,否则比较的对象的地址值
map.put(stu1, "杭州");
map.put(stu2, "广州");
Set<Map.Entry<Student, String>> entries = map.entrySet();
for(Map.Entry<Student, String> keyValue: entries){
Student key = keyValue.getKey();
String value = keyValue.getValue();
System.out.println(key.getName()+":"+key.getAge()+": "+value);
}
//---------------result--------------------------
李茂贞:26: 深圳
李淳风:25: 北京
尤川:26: 广州
袁天罡:30: 上海
ArrayList<HashMap<String, String>> list = new ArrayList<>();
HashMap<String, String> map1 = new HashMap<String, String>();
HashMap<String, String> map2 = new HashMap<String, String>();
HashMap<String, String> map3 = new HashMap<String, String>();
map1.put("张无忌","倚天");
map1.put("张三丰","倚天");
map2.put("段誉","天龙八部");
map2.put("虚竹","天龙八部");
map3.put("杨过","神雕侠侣");
map3.put("神雕","神雕侠侣");
list.add(map1);
list.add(map2);
list.add(map3);
for(HashMap<String, String> map: list){
for(String key: map.keySet()){
System.out.println(key + ": "+map.get(key));
}
}
/*
张三丰: 倚天
张无忌: 倚天
段誉: 天龙八部
虚竹: 天龙八部
杨过: 神雕侠侣
神雕: 神雕侠侣
*/
HashMap<String, ArrayList<String>> map = new HashMap<>();
ArrayList<String> list1 = new ArrayList<>();
ArrayList<String> list2 = new ArrayList<>();
ArrayList<String> list3 = new ArrayList<>();
list1.add("李淳风");
list1.add("袁天罡");
list2.add("李茂贞");
list2.add("李星云");
list3.add("侯清");
list3.add("旱魃");
map.put("风水大师", list1);
map.put("李唐", list2);
map.put("尸祖", list3);
Set<String> keySet = map.keySet();
for(String key: keySet){
ArrayList<String> list = map.get(key);
System.out.println(key + ": " + list);
}
风水大师: [李淳风, 袁天罡]
尸祖: [侯清, 旱魃]
李唐: [李茂贞, 李星云]
Scanner scan = new Scanner(System.in);
System.out.println("请输入要统计的字符串:");
String input = scan.next();
char[] chars = input.toCharArray();
TreeMap<Character, Integer> map = new TreeMap<>();
for(Character cha: chars){
if(map.containsKey(cha)){
map.put(cha, map.get(cha)+1);
}else{
map.put(cha, 1);
}
}
//遍历
for(Character key: map.keySet()){
Integer value = map.get(key);
System.out.print(key + "(" + value + ")");
}
//---------------result--------------------
请输入要统计的字符串:
qweasdqweaa
a(3)d(1)e(2)q(2)s(1)w(2)
-
Collections集合工具类
Collections类的作用:是针对集合操作的工具类
Collections类常用方法
方法名 | 说明 |
public static void sort(List list) | 将指定的列表按升序排序 |
public static void reverse(List<?> list) | 反转指定列表中元素的顺序 |
public static void shuffle(List<?> list) | 使用默认的随机源随机排列指定的列表 |
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(90);
list.add(50);
list.add(30);
System.out.println(list);
//升序排序
Collections.sort(list);
System.out.println(list);
//反转列表
Collections.reverse(list);
System.out.println(list);
//随机排序(洗牌)
Collections.shuffle(list);
System.out.println(list);
/*
[10, 90, 50, 30]
[10, 30, 50, 90]
[90, 50, 30, 10]
[30, 50, 90, 10]
*/
ArrayList<Student> list = new ArrayList<>();
Student stu1 = new Student("李淳风", 25);
Student stu2 = new Student("李茂贞", 24);
Student stu3 = new Student("李星云", 20);
Student stu4 = new Student("袁天罡", 25);
list.add(stu4);
list.add(stu2);
list.add(stu3);
list.add(stu1);
//使用Collections.sort()进行排序
//给定一个比较器,采用匿名类部类的方式声明
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
//按照年龄从小到大排序
int num = s1.getAge() - s2.getAge();
int num2 = num==0?s1.getName().compareTo(s2.getName()): num;
return num2;
}
});
for(Student s: list){
System.out.println("姓名: " + s.getName() + ", 年龄: " + s.getAge());
}
/*
姓名: 李星云, 年龄: 20
姓名: 李茂贞, 年龄: 24
姓名: 李淳风, 年龄: 25
姓名: 袁天罡, 年龄: 25
*/
public static void main(String[] args) throws ParseException {
HashMap<Integer, String> map = new HashMap<>();
//生成扑克牌
String[] colors = {"♥", "♦", "♠", "♣"};
String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
int index = 0;
for(String num: numbers){
for(String color: colors){
map.put(index, color+num);
index++;
}
}
map.put(index, "小王");
index++;
map.put(index, "大王");
ArrayList<Integer> list = new ArrayList<>(map.keySet());
//洗牌
Collections.shuffle(list);
TreeSet<Integer> player_1 = new TreeSet<>();
TreeSet<Integer> player_2 = new TreeSet<>();
TreeSet<Integer> player_3 = new TreeSet<>();
TreeSet<Integer> cards = new TreeSet<>();
//发牌
for(int i=0; i<list.size(); i++){
Integer poker = list.get(i);
if(i >= list.size()-3) {
cards.add(poker);
}else if(i % 3 == 0){
player_1.add(poker);
}else if(i % 3 == 1){
player_2.add(poker);
}else if(i % 3 == 2){
player_3.add(poker);
}
}
//看牌
show(player_1, map);
show(player_2, map);
show(player_3, map);
show(cards, map);
}
public static void show(TreeSet<Integer> set, HashMap<Integer, String> map){
String reuslt = "[";
for(Integer i: set){
reuslt += map.get(i) + ", ";
}
reuslt = reuslt.substring(0, reuslt.length()-2);
System.out.println(reuslt + "]");
}
/*
[♦3, ♣4, ♣5, ♥6, ♦6, ♦7, ♠7, ♥9, ♠10, ♣10, ♥J, ♥Q, ♦Q, ♠Q, ♣Q, ♠K, ♣2]
[♥3, ♣3, ♠4, ♦5, ♣6, ♥7, ♦8, ♠8, ♠9, ♣9, ♦10, ♦J, ♠J, ♦K, ♣K, ♦A, ♣A]
[♠3, ♥4, ♦4, ♥5, ♠6, ♣7, ♥8, ♣8, ♦9, ♥10, ♣J, ♥K, ♥A, ♠A, ♥2, ♠2, 大王]
[♠5, ♦2, 小王]
*/