ArrayList 相关应用
一、ArrayList实现简单扑克牌
//牌类
class Card{
public int rank; // 牌面值
public String suit; // 花色
@Override
public String toString() {
return String.format("[%s %d]", suit, rank);
}
}
public class TestArraylist3 {
public static final String[] SUITS = {"♠", "♥", "♣", "♦"};
// 买一副牌(利用List特点生成一副牌)
private static List<Card> buyDeck() {
List<Card> deck = new ArrayList<>(52);
for (int i = 0; i < 4; i++) {
for (int j = 1; j <= 13; j++) {
String suit = SUITS[i];
int rank = j;
Card card = new Card();
card.rank = rank;
card.suit = suit;
deck.add(card);
}
}
return deck;
}
private static void swap(List<Card> deck, int i, int j) {
Card t = deck.get(i);
deck.set(i, deck.get(j));
deck.set(j, t);
}
//洗牌操作
private static void shuffle(List<Card> deck) {
Random random = new Random(20190905);
for (int i = deck.size() - 1; i > 0; i--) {
int r = random.nextInt(i);
swap(deck, i, r);
}
}
public static void main(String[] args) {
List<Card> deck = buyDeck();
System.out.println("顺序牌展示:");
System.out.println(deck);
shuffle(deck);
System.out.println("洗过的牌展示:");
System.out.println(deck);
// 三个人,每个人轮流抓 5 张牌
List<List<Card>> hands = new ArrayList<>();
hands.add(new ArrayList<>());
hands.add(new ArrayList<>());
hands.add(new ArrayList<>());
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
hands.get(j).add(deck.remove(0));
}
}
System.out.println("剩余的牌:");
System.out.println(deck);
System.out.println("A 手中的牌:");
System.out.println(hands.get(0));
System.out.println("B 手中的牌:");
System.out.println(hands.get(1));
System.out.println("C 手中的牌:");
System.out.println(hands.get(2));
}
}
结果展示:
二、 利用ArrayList储存学生信息
class Student{
private String name;
private int age;
private double scaore;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", scaore=" + scaore +
'}';
}
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 double getScaore() {
return scaore;
}
public void setScaore(double scaore) {
this.scaore = scaore;
}
public Student(String name, int age, double scaore) {
this.name = name;
this.age = age;
this.scaore = scaore;
}
}
public class TestArraylist2 {
public static void main(String[] args) {
List<Student> list =new ArrayList<>(3);
list.add(new Student("梨花",13,89.6));
list.add(new Student("张三",34,76.5));
list.add(new Student(" lisi ",45,90));
System.out.println(list);
}
}
三、删除字符串中的重复元素
删除字符串中与子字符串重复的元素
public class TestArraylist3 {
public static ArrayList<Character> delete(String str1, String str2){
ArrayList<Character> arrayList = new ArrayList<>();
for (int i = 0; i < str1.length(); i++) {
char ch = str1.charAt(i);
//将字符转化为字符串
if(!str2.contains(ch+"")){
arrayList.add(ch);
}
}
return arrayList;
}
public static void main(String[] args) {
ArrayList<Character> ret = delete("welcome to bit","come");
for(int i = 0; i < ret.size();i++){
System.out.print(ret.get(i));
}
}
}