当前位置: 首页 > >

集合之LinkedList案例??生成扑克牌、逆序排序

发布时间:

一、LinkedList案例??生成扑克牌
1、需求:使用LinkedList存储一副扑克牌,然后实现洗牌功能。


2、实现代码:


import java.util.LinkedList;
import java.util.Random;

//扑克类
class Poker{
String color; //花色
String num; //点数

public Poker(String color, String num) {
super();
this.color = color;
this.num = num;
}

public String toString() {
return "{"+color+num+"}";
}
}

public class Demo7 {
public static void main(String[] args){
LinkedList pokers = createPoker();
System.out.println("生产的扑克牌为:");
showPoker(pokers);
shufflePoker(pokers);
System.out.println();
System.out.println("洗牌后的扑克牌为:");
showPoker(pokers);
}

//生成扑克牌的方法
public static LinkedList createPoker(){
//该集合用于存储扑克对象。
LinkedList list = new LinkedList();
//定义数组存储所有的花色与点数
String[] colors = {"黑桃","红桃","梅花","方块"};
String[] nums = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
for(int i=0;i for(int j=0;j list.add(new Poker(colors[i],nums[j]));
}
}
return list;
}

//显示扑克牌
public static void showPoker(LinkedList pokers){
for(int i=0;i System.out.print(pokers.get(i));
//注意:这里的条件是9
if(i%10==9){
System.out.println();
}
}
}
//洗牌的功能
public static void shufflePoker(LinkedList pokers){
//创建随机数对象
Random random = new Random();
for (int i=0; i<100; i++){
//随机产生两个索引值
//注意:有范围要求,而为什么pokers.size()不减1,因为next会自动下移一个单位
int index1 = random.nextInt(pokers.size());
int index2 = random.nextInt(pokers.size());
//根据索引值取出两张牌,然后交换两张牌的顺序
Poker poker1 = (Poker) pokers.get(index1);
Poker poker2 = (Poker) pokers.get(index2);
pokers.set(index1, poker2);
pokers.set(index2, poker1);
}
}
}

3、效果:


二、LinkedList案例??逆序排序
1、需求:编写一个函数根据人的年龄及逆行排序存储。


2、实现代码:


import java.util.LinkedList;

class Student{

String name;

int age;

public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}

public String toString() {
return "{ 名字:"+ this.name+" 年龄:"+ this.age+"}";
}
}

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

LinkedList list = new LinkedList();
list.add(new Student("Lucy",20));
list.add(new Student("Endeavor",21));
list.add(new Student("Lily",18));

//根据人的年龄及逆行排序存储。
//采用直接排序算法
for(int i=0;i for(int j=i+1;j //符合条件交换位置
Student s1 = (Student)list.get(i);
Student s2 = (Student)list.get(j);
if(s1.age>s2.age){
//交换位置
list.set(i, s2);
list.set(j, s1);
}
}
}
System.out.println(list);
}
}

3、效果:



友情链接: