欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 集合框架之List 的使用(附小游戏练习)

程序员文章站 2023-12-31 15:01:58
目录1. list1.1 list 的常见方法2. arraylist2.2 arraylist 的构造方法2.3 arraylist 底层数组的大小3. linkedlist3.2 linkedli...

1. list

1.1 list 的常见方法

Java 集合框架之List 的使用(附小游戏练习)

1.2 代码示例

注意: 下面的示例都是一份代码分开拿出来的,上下其实是有逻辑关系的

示例一: 用 list 构造一个元素为整形的顺序表

list<integer> list = new arraylist<>();

示例二: 尾插 e

list.add(1);
list.add(2);
system.out.println(list);
// 结果为:[1, 2]

示例三: 将 e 插入到 index 位置

list.add(0,10);
system.out.println(list);
// 结果为:[10, 1, 2]

示例四: 尾插 c 中的元素

list<integer> list1=new linkedlist<>();
list1.add(99);
list1.add(100);
list.addall(list1);
system.out.println(list);
// 结果为:[10, 1, 2, 99, 100]

只要是继承于 collection 的集合类的元素都可以被插入进去,但要注意传过来的具体的类型要么是和 list 的具体类型是一样的,要么是 list 具体类型的子类

示例五: 删除 index 位置的元素

system.out.println(list.remove(0));
system.out.println(list);
// 结果为:10 和 [1, 2, 99, 100]

示例六: 删除遇到的第一个 o

system.out.println(list.remove((integer) 100));
system.out.println(list);
// 结果为:true 和 [1, 2, 99]

示例七: 获取下标 index 位置的元素

system.out.println(list.get(0));
// 结果为:1

示例八: 将下标 index 位置元素设置为 element

system.out.println(list.set(2,3));
system.out.println(list);
// 结果为:99 和 [1, 2, 3]

示例九: 判断 o 是否在线性表中

system.out.println(list.contains(1));
// 结果为:true

示例十: 返回第一个 o 所在下标

system.out.println(list.indexof(1));
// 结果为:0

示例十一: 返回最后一个 o 的下标

list.add(1);
system.out.println(list.lastindexof(1));
// 结果为:3

示例十二: 截取部分 list

list<integer> list2=list.sublist(1,3);
system.out.println(list2);
// 结果为:[2, 3]

注意:当我们将 list2 通过 set 更改元素,其实对 list 也会有影响

list2.set(0,5);
system.out.println(list2);
system.out.println(list);
// 结果为:[5, 3] 和 [1, 5, 3, 1]

通过 sublist 方法进行的截取,得到的集合的数值指向的地址和原集合中数值的地址是一样的

2. arraylist

2.1 介绍

arraylist 类是一个可以动态修改的数组,与普通数组的区别就是它是没有固定大小的限制,我们可以添加或删除元素。其继承了 abstractlist,并实现了 list 接口。linkedlist 不仅实现了 list 接口,还实现了 queue deque 接口,可以作为队列去使用。

arraylist 类位于 java.util 包中,使用前需要引入它。

2.2 arraylist 的构造方法

方法 描述
arraylist() 无参构造
arraylist(collection<? extends e> c) 利用其他 collection 构建 arraylist
arraylist(int initialcapacity) 指定顺序表初始容量

示例一:

arraylist<integer> list1 = new arraylist<>();

示例二:

arraylist<integer> list2 = new arraylist<>(10);
// 该构造方法就是在构建时就将底层数组大小设置为了10

示例三:

list<integer> list = new arraylist<>();
list.add(1);
list.add(2);
arraylist<integer> list3 = new arraylist<>(list);

collection<? extends e> c 只要是具体类型都和 list3 是一样的集合都可以放入转化成 arraylist

2.3 arraylist 底层数组的大小

当我们使用 add 方法给 arraylist 的对象进行尾插时,突然想到了一个问题:既然 arraylist 的底层是一个数组,那么这个数组有多大呢?

为了解决这个问题,我进行了如下探索

跳转到 arraylist 的定义,我们看到了 elementdata defaultcapacity_empty_elementdata

Java 集合框架之List 的使用(附小游戏练习)

跳转到 elementdata 的定义,我们可以了解 arraylist 底层是数组的原因

Java 集合框架之List 的使用(附小游戏练习)

跳转到 defaultcapacity_empty_elementdata 的定义,初步分析得到这个数组其实是空的

Java 集合框架之List 的使用(附小游戏练习)

为什么这个数组是空的但存储元素的时候没有报异常呢?我们再去了解下 add 是怎样存储的

(1)通过转到 arraylist add 方法的定义

Java 集合框架之List 的使用(附小游戏练习)

(2)通过定义,不难发现,数组容量和 ensurecapacityinternal 这个东西有关,那我们就看看它的定义

Java 集合框架之List 的使用(附小游戏练习)

(3)我们看里面的 calculatecapacity ,他有两个参数,此时数组为空,那么 mincapacity 就为 1。我们再转到 calculatecapacity 看看它的定义

Java 集合框架之List 的使用(附小游戏练习)

(4)此时我们就好像可以与之前串起来了,当数组为 defaultcapacity_empty_elementdata 时,就返回default_capacity mincapacity(此时为1) 的最大值。default_capacity 其实是默认容量的意思,我们可以转到它的定义看看有多大

Java 集合框架之List 的使用(附小游戏练习)

(5)default_capacity 的值是10,故 calculatecapacity 函数此时的返回值为10,最后我们再确定一下 ensureexplicitcapacity 是干啥的

Java 集合框架之List 的使用(附小游戏练习)

(6)此时 mincapacity 的值是10,而数组为空时数组长度为0,所以进入 if 语句,执行 grow 方法,我们继续转到 grow 的定义

Java 集合框架之List 的使用(附小游戏练习)

此时我们就可以了解,当我们创建一个 arraylist 时,其底层数组大小其实是0。当我们第一次 add 的时候,经过 grow ,数组的大小就被扩容为了10。并且这大小为10的容量放满以后,就会按1.5倍的大小继续扩容。至于这个数组最大能存放多少,大家可以再转到 max_array_size 的定义去查看。

3. linkedlist

3.1 介绍

linkedlist 类是一种常见的基础数据结构,是一种线性表,但是并不会按线性的顺序存储数据,而是在每一个节点里存到下一个节点的地址。

java linkedlist 底层是一个双向链表,位于 java.util 包中,使用前需要引入它

3.2 linkedlist 的构造方法

方法 描述
linkedlist() 无参构造
linkedlist(collection<? extends e> c) 利用其他 collection 构建 linkedlist

示例一:

linkedlist<integer> list1 = new linkedlist<>();


示例二:

list<integer> list = new linkedlist<>();
list.add(1);
list.add(2);
linkedlist<integer> list2 = new linkedlist<>(list);

collection<? extends e> c 只要是具体类型都和 list2 是一样的集合都可以放入转化成 linkedlist

4. 练习题

习题一

题目描述:

霍格沃茨学院有若干学生(学生对象放在一个 list 中),每个学生有一个姓名(string)、班级(string)和考试成绩(double)。某次考试结束后,每个学生都获得了一个考试成绩。遍历 list 集合,并把每个学生对象的属性都打印出来

本题代码:

class student{
    private string name;
    private string classes;
    private double score;
 // 重写构造方法
    public student(string name, string classes, double score) {
        this.name = name;
        this.classes = classes;
        this.score = score;
    }
 // 构造 get 和 set 方法
    public string getname() {
        return name;
    }

    public void setname(string name) {
        this.name = name;
    }

    public string getclasses() {
        return classes;
    }

    public void setclasses(string classes) {
        this.classes = classes;
    }

    public double getscore() {
        return score;
    }

    public void setscore(double score) {
        this.score = score;
    }
 // 重写 tostring 方法
    @override
    public string tostring() {
        return "student{" +
                "name='" + name + '\'' +
                ", classes='" + classes + '\'' +
                ", score=" + score +
                '}';
    }
}
public class testdemo {
    public static void main(string[] args) {
        arraylist<student> students = new arraylist<>();
        students.add(new student("哈利波特","大二班",95.5));
        students.add(new student("赫敏格兰杰","小三班",93));
        students.add(new student("罗恩韦斯莱","小二班",91));
        for(student s: students){
            system.out.println(s);
        }   
    }
}
// 结果为:
// student{name='哈利波特', classes='大二班', score=95.5}
// student{name='赫敏格兰杰', classes='小三班', score=93.0}
// student{name='罗恩韦斯莱', classes='小二班', score=91.0}

习题二

题目描述:

有一个 list 当中存放的是整形的数据,要求使用 collections.sort list 进行排序

该题代码:

public class testdemo {
    public static void main(string[] args) {
        arraylist<integer> list = new arraylist<>();
        list.add(3);
        list.add(7);
        list.add(1);
        list.add(6);
        list.add(2);
        collections.sort(list);
        system.out.println(list);
    }
}
// 结果为:[1, 2, 3, 6, 7]

补充:

collections 是一个工具类,sort 是其中的静态方法,它是用来对 list 类型进行排序的

注意:

如果具体的类是类似于习题一那样的 student 类,该类中含有多个属性,那就不能直接使用这个方法。要对 comparator 或者 comparable 接口进行重写,确定比较的是哪个属性才行

习题三

题目描述:

输出删除了第一个字符串当中出现的第二个字符串中的字符的字符串,例如

string str1 = "welcome to harrypotter";
string str2 = "come";
// 结果为:wl t harrypttr

希望本题可以使用集合来解决

该题代码:

public static void removes(string str1, string str2){
    if(str1==null || str2==null){
        return;
    }
    list<character> list = new arraylist<>();
    int lenstr1=str1.length();
    for(int i=0; i<lenstr1; i++){
        char c = str1.charat(i);
        if(!str2.contains(c+"")){
            list.add(c);
        }
    }
    for(char ch: list){
        system.out.print(ch);
    }
}

5. 扑克牌小游戏

我们可以通过上述所学,运用 list 的知识,去写一个关于扑克牌的逻辑代码(如:获取一副牌、洗牌、发牌等等)

class card{
    private string suit;   // 花色
    private int rank;       // 牌面值
    public card(string suit, int rank){
        this.suit=suit;
        this.rank=rank;
    }
    @override
    public string tostring() {
        return "[ "+suit+" "+rank+" ] ";
    }
}
public class testdemo {
    public static string[] suits = {"♣", "♦", "♥", "♠"};
    // 获取一副牌
    public static list<card> getnewcards(){
        // 存放 52 张牌
        list<card> card = new arraylist<>();
        for(int i=0; i<4; i++){
            for(int j=1; j<=13; j++) {
                card.add(new card(suits[i], j));
            }
        }
        return card;
    }
    public static void swap(list<card> card, int i, int j){
        card tmp = card.get(i);
        card.set(i, card.get(j));
        card.set(j, tmp);
    }
    // 洗牌
    public static void shuffle(list<card> card){
        int size = card.size();
        for(int i=size-1; i>0; i--){
            random random = new random();
            int randnum = random.nextint(i);
            swap(card, i, randnum);
        }
    }
    public static void main(string[] args) {
        // 得到一副新的牌
        list<card> cardlist = getnewcards();
        system.out.println("已获取新的扑克牌");
        system.out.println("洗牌:");
        shuffle(cardlist);
        system.out.println(cardlist);
        system.out.println("抓牌:(3个人,每人轮流抓牌总共抓5张)");
        list<card> hand1 = new arraylist<>();
        list<card> hand2 = new arraylist<>();
        list<card> hand3 = new arraylist<>();
        list<list<card>> hands = new arraylist<>();
        hands.add(hand1);
        hands.add(hand2);
        hands.add(hand3);
        for(int i=0; i<5; i++){
            for(int j=0; j<3; j++){
                card card = cardlist.remove(0);
                hands.get(j).add(card);
            }
        }
        system.out.println("第一个人的牌:"+hand1);
        system.out.println("第二个人的牌:"+hand2);
        system.out.println("第三个人的牌:"+hand3);
    }
}
/** 
结果为:
已获取新的扑克牌
洗牌:
[[ ♥ 9 ] , [ ♦ 6 ] , [ ♣ 8 ] , [ ♦ 2 ] , [ ♣ 6 ] , [ ♦ 4 ] , [ ♣ 11 ] , [ ♣ 9 ] , [ ♠ 8 ] , [ ♣ 5 ] , [ ♦ 8 ] , [ ♦ 10 ] , [ ♦ 1 ] , [ ♦ 12 ] , [ ♥ 10 ] , [ ♥ 7 ] , [ ♠ 12 ] , [ ♥ 12 ] , [ ♦ 7 ] , [ ♣ 13 ] , [ ♠ 6 ] , [ ♠ 5 ] , [ ♥ 3 ] , [ ♦ 5 ] , [ ♦ 11 ] , [ ♣ 12 ] , [ ♠ 7 ] , [ ♦ 3 ] , [ ♥ 5 ] , [ ♦ 13 ] , [ ♣ 1 ] , [ ♥ 8 ] , [ ♠ 10 ] , [ ♠ 4 ] , [ ♣ 4 ] , [ ♣ 7 ] , [ ♥ 1 ] , [ ♠ 1 ] , [ ♣ 3 ] , [ ♥ 11 ] , [ ♥ 13 ] , [ ♦ 9 ] , [ ♠ 13 ] , [ ♣ 10 ] , [ ♥ 6 ] , [ ♠ 11 ] , [ ♠ 3 ] , [ ♣ 2 ] , [ ♠ 2 ] , [ ♥ 2 ] , [ ♥ 4 ] , [ ♠ 9 ] ]
抓牌:(3个人,每人轮流抓牌总共抓5张)
第一个人的牌:[[ ♥ 9 ] , [ ♦ 2 ] , [ ♣ 11 ] , [ ♣ 5 ] , [ ♦ 1 ] ]
第二个人的牌:[[ ♦ 6 ] , [ ♣ 6 ] , [ ♣ 9 ] , [ ♦ 8 ] , [ ♦ 12 ] ]
第三个人的牌:[[ ♣ 8 ] , [ ♦ 4 ] , [ ♠ 8 ] , [ ♦ 10 ] , [ ♥ 10 ] ]
*/

上述代码中有一处代码是这样写的 list<list<card>> ,其实不难理解,这个类型其实就是 list 中存放的每个元素都是一个 list 类型的,并且每一个 list 元素中的元素都是 card 类型,类似于二维数组。

到此这篇关于java 集合框架之list 的使用(附小游戏练习)的文章就介绍到这了,更多相关java list 的使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: Java List

上一篇:

下一篇: