Java——Collections 2-6

Collections

Collenctions overview and use

Overview of the Collections class

  • Is a tool class for collection operations

Common methods of the Collections class

  • public static <T extends Comparable<? super T>> void sort(List list): Sort the specified list in ascending order
  • public static void reverse(List<?> list): Reverse the order of the elements in the specified list
  • public static void shuffle(List<?> list): Randomly shuffle the specified list using the default random source

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/*
Collections类的概述

- 是针对集合操作的工具类

Collections类的常用方法

- public static <T extends Comparable<? super T>> void sort(List<T> list):将指定的列表按升序排序
- public static void reverse(List<?> list):反转指定列表中元素的顺序
- public static void shuffle(List<?> list):使用默认的随机源随机排列指定的列表



*/

public class CollectionsDemo {
    
    
	public static void main(String[] args) {
    
    
		//创建List集合对象
		List<Integer> list = new ArrayList<Integer>();

		//添加元素
		list.add(10);
		list.add(20);
		list.add(40);
		list.add(60);
		list.add(50);

		//		public static <T extends Comparable<? super T>> void sort(List<T> list):将指定的列表按升序排序
		Collections.sort(list);
		/*运行结果:
		[10, 20, 40, 50, 60]
		*/

		//		public static void reverse(List<?> list):反转指定列表中元素的顺序
		Collections.reverse(list);
		/*运行结果:反转列表中元素的顺序
		[50, 60, 40, 20, 10]
		*/

		//		public static void shuffle(List<?> list):使用默认的随机源随机排列指定的列表
		Collections.shuffle(list);
		/*运行结果:随机排序  每次运行会出现不同的结果
		[10, 60, 20, 50, 40]
		*/

		System.out.println(list);

	}
}

Case: ArrayList stores and sorts student objects

Requirements: ArratLIst stores student objects, and uses Collections to sort ArrayList
Requirements: Sort by age from young to old, and when the age is the same, sort by name alphabetically


//定义学生类
public class Student {
    
    
	private String name;
	private int 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 Student(String name, int age) {
    
    
		super();
		this.name = name;
		this.age = age;
	}

	public Student() {
    
    
		super();
	}

}

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/*
案例:ArrayList存储学生对象并排序

需求:ArratLIst存储学生对象,使用Collections对ArrayList进行排序
	要求:按照年龄从小到大的排序,年龄相同时,按照姓名的字母顺序排序

*/
public class ArrayListDemo {
    
    
	public static void main(String[] args) {
    
    
		//创建ArrayList集合对象
		ArrayList<Student> array = new ArrayList<Student>();

		//创建学生对象
		Student s1 = new Student("小白", 12);
		Student s2 = new Student("小黑", 11);
		Student s3 = new Student("小蓝", 14);
		Student s4 = new Student("小红", 15);

		//把学生添加到集合中
		array.add(s1);
		array.add(s2);
		array.add(s3);
		array.add(s4);

		//使用Collections对集合排序
		//sort (List<T> list,Comparator<? super T>)
		Collections.sort(array, 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 : array) {
    
    
			System.out.println(s.getName() + "," + s.getAge());
		}

	}
}

operation result:
insert image description here

Case: Simulation of Fighting the Landlords

Requirements: Realize the shuffling, dealing and viewing of cards in the process of fighting landlords through programs
. Ideas:

  1. Create a card box, that is, define a collection object, and implement it with the ArrayList collection
  2. Put the cards in the box
  3. Shuffle, that is, to scatter the cards, using the shuffle() method of Collections
  4. Dealing cards, that is, traversing the collection, and dealing cards to three players
  5. Look at the cards, that is, the three players traverse their own cards respectively
import java.util.ArrayList;
import java.util.Collections;

/*
案例:模拟斗地主

需求:通过程序实现斗地主过程中的洗牌,发牌和看牌

思路:
 1. 创建一个牌盒,也就是定义一个集合对象,用ArrayList集合实现
 2. 往牌盒里面装牌
 3. 洗牌,也就是把牌打撒,用Collections的shuffle()方法实现
 4. 发牌,也就是遍历集合,给三个玩家发牌
 5. 看牌,也就是三个玩家分别遍历自己的牌

*/

public class PoKerDemo {
    
    
	public static void main(String[] args) {
    
    

		//		1. 创建一个牌盒,也就是定义一个集合对象,用ArrayList集合实现
		ArrayList<String> array = new ArrayList<String>();

		//		 2. 往牌盒里面装牌
		/*
		♦2,♦3,♦4。。。♦K,♦A
		♣。。。
		♥。。。
		♠。。。
		小王 大王
		*/

		//定义花色数组
		String[] colors = {
    
     "♦", "♣", "♥", "♠" };
		//定义点数数组
		String[] numbers = {
    
     "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };

		for (String color : colors) {
    
    
			for (String num : numbers) {
    
    
				array.add(color + num);
			}
		}
		array.add("小王");
		array.add("大王");

		//		System.out.println(array);

		//		 3. 洗牌,也就是把牌打撒,用Collections的shuffle()方法实现
		Collections.shuffle(array);

		//		 4. 发牌,也就是遍历集合,给三个玩家发牌
		//创建三个玩家
		ArrayList<String> xiao = new ArrayList<String>();
		ArrayList<String> hei = new ArrayList<String>();
		ArrayList<String> bai = new ArrayList<String>();
		//底牌
		ArrayList<String> dpArray = new ArrayList<String>();

		for (int i = 0; i < array.size(); i++) {
    
    
			String poker = array.get(i);//得到牌

			if (i >= array.size() - 3) {
    
    //最后三张牌
				dpArray.add(poker);
			} else if (i % 3 == 0) {
    
    //对三个玩家取余
				xiao.add(poker);
			} else if (i % 3 == 1) {
    
    
				hei.add(poker);
			} else if (i % 3 == 2) {
    
    
				bai.add(poker);
			}
		}

		//		 5. 看牌,也就是三个玩家分别遍历自己的牌
		lookPoker("小小", xiao);
		lookPoker("小黑", hei);
		lookPoker("小白", bai);
		lookPoker("底牌", dpArray);

	}

	//看牌的方法
	public static void lookPoker(String name, ArrayList<String> array) {
    
    
		System.out.print(name + "的牌是:");
		for (String poker : array) {
    
    
			System.out.print(poker + " ");
		}
		System.out.println();//换行
	}

}

operation result:
insert image description here

Case: Simulated Battle of the Landlords (upgrade)

Requirements: Realize the shuffling, dealing and viewing of cards in the process of fighting the landlord through the program. Requirement: Sort the cards
Ideas:

  1. Create a HashMap, the key is the number, and the value is the card
  2. Create an ArrayList to store the number
  3. Create an array of suits and an array of points
  4. Store numbers in HashMap starting from 0, store corresponding cards, and store numbers in ArrayList at the same time
  5. Shuffle (shuffling is the number), implemented with the shuffle() method of Collections
  6. Dealing cards (the cards issued are also numbered, in order to ensure that the numbers are sorted, create a TreeSet collection to receive)
  7. Define the method to look at the cards (traverse the TreeSet collection, obtain the code, and find the corresponding card in the HashMap collection)
  8. call check method
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.TreeSet;

/*
案例:模拟斗地主(升级)

需求:通过程序实现斗地主过程中的洗牌,发牌和看牌。要求:对牌进行排序
思路:

 1. 创建HashMap,键是编号,值是牌
 2. 创建ArrayList,存储编号
 3. 创建花色数组和点数数组
 4. 从0开始往HashMap里面存储编号,并存储对应的牌,同时往ArrayList里面存储编号
 5. 洗牌(洗的是编号),用Collections的shuffle()方法实现
 6. 发牌(发的牌也是编号,为了保证编号是排序的,创建TreeSet集合接收)
 7. 定义方法看牌(遍历TreeSet集合,获取编码,到HashMap集合找对应的牌)
 8. 调用看牌方式

*/

public class PoKerDemo2 {
    
    
	public static void main(String[] args) {
    
    
		//		1. 创建HashMap,键是编号,值是牌
		HashMap<Integer, String> hm = new HashMap<Integer, String>();

		//		 2. 创建ArrayList,存储编号
		ArrayList<Integer> array = new ArrayList<Integer>();

		//		 3. 创建花色数组和点数数组
		String[] colors = {
    
     "♦", "♣", "♠", "♥" };
		String[] numbers = {
    
     "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2" };

		//		 4. 从0开始往HashMap里面存储编号,并存储对应的牌,同时往ArrayList里面存储编号
		int index = 0;
		for (String color : colors) {
    
    
			for (String num : numbers) {
    
    
				hm.put(index, color + num);
				array.add(index);
				index++;
			}
		}
		hm.put(index, "小王");
		array.add(index);
		index++;
		hm.put(index, "大王");
		array.add(index);

		//		 5. 洗牌(洗的是编号),用Collections的shuffle()方法实现
		Collections.shuffle(array);

		//		 6. 发牌(发的牌也是编号,为了保证编号是排序的,创建TreeSet集合接收)
		TreeSet<Integer> bai = new TreeSet<Integer>();
		TreeSet<Integer> hei = new TreeSet<Integer>();
		TreeSet<Integer> hong = new TreeSet<Integer>();
		TreeSet<Integer> dpSet = new TreeSet<Integer>();

		for (int i = 0; i < array.size(); i++) {
    
    
			int x = array.get(i);
			if (i >= array.size() - 3) {
    
    
				dpSet.add(x);
			} else if (i % 3 == 0) {
    
    
				bai.add(x);
			} else if (i % 3 == 1) {
    
    
				hei.add(x);
			} else if (i % 3 == 2) {
    
    
				hong.add(x);
			}

		}

		//		 8. 调用看牌方式
		look("小白", bai, hm);
		look("小黑", hei, hm);
		look("小红", hong, hm);
		look("底牌", dpSet, hm);

	}

	//		 7. 定义方法看牌(遍历TreeSet集合,获取编码,到HashMap集合找对应的牌)
	public static void look(String name, TreeSet<Integer> ts, HashMap<Integer, String> hm) {
    
    
		System.out.print(name + "的牌是:");
		for (Integer key : ts) {
    
    
			String poker = hm.get(key);
			System.out.print(poker + " ");
		}
		System.out.println();

	}
}

operation result:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_47678894/article/details/119498206