Java:数据结构-ArrayList和顺序表(2)

news2024/10/10 5:59:07

一 ArrayList的使用

1.ArrayList的构造方法

第一种(指定容量的构造方法)

创建一个空的ArrayList,指定容量为initialCapacity。

public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

第二种(无参的构造方法)

创建一个空的ArrayList,默认容量为10

public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

第三种(集合构造方法)

创建一个ArrayList,并将指定集合c中的元素复制到新的ArrayList中

public ArrayList(Collection<? extends E> c) {
        Object[] a = c.toArray();
        if ((size = a.length) != 0) {
            if (c.getClass() == ArrayList.class) {
                elementData = a;
            } else {
                elementData = Arrays.copyOf(a, size, Object[].class);
            }
        } else {
            // replace with empty array.
            elementData = EMPTY_ELEMENTDATA;
        }
    }

2.ArrayList的三种遍历

 1.for循环遍历

public class Test<E> {
    public static void main(String[] args) {
        ArrayList<Integer> arrayList=new ArrayList<>();
        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3);
        arrayList.add(4);
        arrayList.add(5);
        int size= arrayList.size();
        for (int i = 0; i < size; i++) {
            System.out.print(arrayList.get(i)+" ");
        }
    }
}

2.foreach遍历

public class Test<E> {
    public static void main(String[] args) {
        ArrayList<Integer> arrayList=new ArrayList<>();
        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3);
        arrayList.add(4);
        arrayList.add(5);
        int size= arrayList.size();
        for (Integer arrayList1:arrayList) {
            System.out.print(arrayList1+" ");
        }
}

3.迭代器遍历

迭代器的遍历可以使用listIterator和Iterator

 public static void main(String[] args) {
        ArrayList<Integer> arrayList=new ArrayList<>();

        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3);
        arrayList.add(4);
        arrayList.add(5);
        int size= arrayList.size();
        ListIterator<Integer> listIterator=arrayList.listIterator();
        while (listIterator.hasNext()){
            Integer s1=listIterator.next();
            System.out.print(s1+" ");
        }
        System.out.println("");

        Iterator<Integer> iterator= arrayList.iterator();
        while (iterator.hasNext()){
            Integer s=iterator.next();
            System.out.print(s+" ");
        }
        System.out.println();
}

但是listIterator可以指定位置

从最后的一位开始遍历,倒序

public class Test<E> {
    public static void main(String[] args) {
        ArrayList<Integer> arrayList=new ArrayList<>();

        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3);
        arrayList.add(4);
        arrayList.add(5);
        int size= arrayList.size();
        ListIterator<Integer> listIterator1=arrayList.listIterator(arrayList.size());
        while (listIterator1.hasPrevious()){
            Integer s2=listIterator1.previous();
            System.out.print(s2+" ");
        }
        System.out.println();
}

二 ArrayList的具体使用

1.杨辉三角形

第一步

首先我们写一个generate方法,将行数作为参数传入,我们可以把杨辉三角形看成一个二维数组,将其实例化为lists,然后我们把第一行实例化为row1,在其中添加1,然后把row1作为第一行添加到lists中。

第二步

写一个关于行数的for循环,将i定义为1,因为第一行已经添加了,然后实例化一个cunRow作为中间的行数,因为杨辉三角形的中间部分的数字等于前一行前一列的数字大小+前一行同一列的数字大小,所以我们要获取前一行的内容,实例row2表示前一行的内容,将前一行前一列的数字大小赋给val1,前一行同一列的数字大小赋给val2,再将其添加到cunRow中。

第三步

在每一行的末尾添加数字1,然后把cunRow添加到lists中,最终构成了杨辉三角形lists。

public class Test<E> {

    public static List<List<Integer>> generate(int numRow){
        List<List<Integer>> lists=new ArrayList<>();
        List<Integer> row1=new ArrayList<>();
        row1.add(1);
        lists.add(row1);


        for (int i = 1; i <numRow; i++) {
            List<Integer> cunRow=new ArrayList<>();
            cunRow.add(1);
            List<Integer> row2=lists.get(i-1);
            for (int j = 1; j < i; j++) {
                int val1=row2.get(j-1);
                int val2=row2.get(j);
                cunRow.add(val1+val2);
            }
            cunRow.add(1);
            lists.add(cunRow);
        }



        return lists;
    }

    public static void main(String[] args) {
        List<List<Integer>> lists=generate(5);
        for (int i = 0; i < lists.size(); i++) {
            for (int j = 0; j < lists.get(i).size(); j++) {

                System.out.print(lists.get(i).get(j));
            }
            System.out.println();
        }
    }

 

2. 简单的洗牌算法

我们可以分为三个部分买牌,洗牌,发牌

(1)买牌

我们把牌中的JQK定义为11,12,13,一个13种数字4中花色。把数字传给rank,花色传给suit,然后用提前写好的类Card,写好构造方法,ToString方法,将rank和suit传给定义好的card。将card添加到cardlist中。

public List<Card> buyCard(){
        List<Card> cardList=new ArrayList<>();
        for (int i = 1; i <=13; i++) {
            for (int j = 0; j < 4; j++) {
                int rank=i;
                String suit=suits[j];
                Card card=new Card(suit,rank);
                cardList.add(card);

            }
        }
        return cardList;
    }

(2)洗牌

先将随机数的类进行实例化,然后从最后一个数开始将i变为随机数index,再写一个swap方法将随机数和原数交换位置,就可以达到洗牌的效果。

public void shuffle(List<Card> cardList){
        Random random=new Random();
        for (int i=cardList.size()-1;i>0;i--){
            int index= random.nextInt(i);
            swap(cardList,index,i);
        }
    }
    public void swap(List<Card> cardList,int i,int j){
        Card tem=cardList.get(i);
        cardList.set(i,cardList.get(j));
        cardList.set(j,tem);
    }

(3)发牌

将三个人实例化为player1,player2,player3,然后将三个对象添加到player中,因为每个人都是从第一张开始揭牌,所以用ArrayList中的remove方法,每次把第一个牌移除,再分别添加到每个人的手中,可以用j代表player的每一行。

public List<List<Card>> play(List<Card> cardList){

        List<Card> player1=new ArrayList<>();
        List<Card> player2=new ArrayList<>();
        List<Card> player3=new ArrayList<>();
        List<List<Card>> player=new ArrayList<>();
        player.add(player1);
        player.add(player2);
        player.add(player3);
        for (int i = 0; i <5 ; i++) {
            for (int j = 0; j < 3; j++) {
                Card card=cardList.remove(0);
                player.get(j).add(card);
            }
        }
        return player;
    }
}

整个过程

public 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 /*"Card{" +
                "suit='" + suit + '\'' +
                ", rank=" + rank +
                '}';*/
        "{"+suit+rank+"}";
    }
}

public class CardDemon {
    public static String[] suits={"♣","♦","♥","♠"};

    public List<Card> buyCard(){
        List<Card> cardList=new ArrayList<>();
        for (int i = 1; i <=13; i++) {
            for (int j = 0; j < 4; j++) {
                int rank=i;
                String suit=suits[j];
                Card card=new Card(suit,rank);
                cardList.add(card);

            }
        }
        return cardList;
    }

    public void shuffle(List<Card> cardList){
        Random random=new Random();
        for (int i=cardList.size()-1;i>0;i--){
            int index= random.nextInt(i);
            swap(cardList,index,i);
        }
    }
    public void swap(List<Card> cardList,int i,int j){
        Card tem=cardList.get(i);
        cardList.set(i,cardList.get(j));
        cardList.set(j,tem);
    }


    public List<List<Card>> play(List<Card> cardList){

        List<Card> player1=new ArrayList<>();
        List<Card> player2=new ArrayList<>();
        List<Card> player3=new ArrayList<>();
        List<List<Card>> player=new ArrayList<>();
        player.add(player1);
        player.add(player2);
        player.add(player3);
        for (int i = 0; i <5 ; i++) {
            for (int j = 0; j < 3; j++) {
                Card card=cardList.remove(0);
                player.get(j).add(card);
            }
        }
        return player;
    }
}

public class Test<E> {


    public static void main(String[] args) {
        //1
        CardDemon cardDemon=new CardDemon();
        List<Card> cardList=cardDemon.buyCard();
        System.out.println(cardList);
        System.out.println();
        //2
        cardDemon.shuffle(cardList);
        System.out.println(cardList);

        //3
        List<List<Card>> s=cardDemon.play(cardList);
        for (int i = 0; i < s.size(); i++) {
            System.out.println("第"+(i+1)+"个人的牌:"+s.get(i));
        }
        System.out.println("剩下的牌");
        System.out.println(cardList);

    }

 

希望能对大家有所帮助!!!!! 

 

 

 

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2201246.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

鸿蒙微内核IPC数据结构

鸿蒙内核IPC数据结构 内核为任务之间的通信提供了多种机制&#xff0c;包含队列、事件、互斥锁、信号量等&#xff0c;其中还有Futex(用户态快速锁)&#xff0c;rwLock(读写锁)&#xff0c;signal(信号)。 队列 队列又称为消息队列&#xff0c;是一种常用于任务间通信的数据…

《ASP.NET Web Forms 实现短视频点赞功能的完整示例》

在现代Web开发中&#xff0c;实现一个动态的点赞功能是非常常见的需求。本文将详细介绍如何在ASP.NET Web Forms中实现一个视频点赞功能&#xff0c;包括前端页面的展示和后端的处理逻辑。我们将确保点赞数量能够实时更新&#xff0c;而无需刷新整个页面。 技术栈 ASP.NET We…

Java进阶之路—单元测试Juint(完整详解Juint使用以及Juin注解,附有代码+案例)

文章目录 单元测试Juint35.1 概述35.2 用法手动导包正确的使用方式 35.3 Junit常用注解 单元测试Juint 35.1 概述 针对最小功能单元编写测试代码&#xff0c;Java中最小功能单元是方法&#xff0c;因此单元测试就是针对Java方法的测试。 对部分代码进行测试。 35.2 用法 &…

【含开题报告+文档+PPT+源码】基于SpringBoot+Vue的新能源停车场管理系统

开题报告 随着新能源汽车的快速普及和普及&#xff0c;新能源车辆的停车和充电需求也越来越大。传统的停车场管理系统无法满足这些新能源车辆的特殊需求&#xff0c;如充电桩分配、充电桩使用情况的实时监测等。因此&#xff0c;开发一种基于 Java 的新能源停车场管理系统成为…

计算机视觉之YOLO算法基本原理和应用场景

YOLO算法基本原理 整体流程 YOLO 将目标检测问题转化为一个回归问题。它将输入图像划分成多个网格单元&#xff0c;每个网格单元负责预测中心点落在该网格内的目标。对于每个网格单元&#xff0c;YOLO 预测多个边界框以及这些边界框中包含目标的类别概率。边界框通常由中心点坐…

Spring Cloud Stream 3.x+kafka 3.8整合

Spring Cloud Stream 3.xkafka 3.8整合&#xff0c;文末有完整项目链接 前言一、如何看官方文档(有深入了解需求的人)二、kafka的安装tar包安装docker安装 三、代码中集成创建一个测试topic&#xff1a;testproducer代码producer配置&#xff08;配置的格式&#xff0c;上篇文章…

PHP中的HTTP请求:简化你的网络通信

在当今的网络应用开发中&#xff0c;PHP作为一种流行的服务器端脚本语言&#xff0c;经常需要与外部服务进行通信。这通常涉及到发送HTTP请求来获取或提交数据。幸运的是&#xff0c;PHP提供了多种方式来简化HTTP请求的过程&#xff0c;使得网络通信变得轻而易举。 PHP中的HTTP…

stm32h743 threadx + filex(SD卡读写) + CubeMX + CubeIDE

今天整了一下正点原子阿波罗h743的filex,按部就班的使用CubeMX去搭建环境,再用CubeIDE去编写程序,里面也有几个小坑,问题不大。 Step1. 创建CubeMX 首先设置RCC晶振,SYS为tim6 然后勾选sdmmc1 选择4bits,分频系数为4。这个分频系数选4对应一般的sd卡都可以用了,如果好…

单片机死机后在不破坏现场的情况下连接调试器进入调试模式

经常遇到程序在现场卡死了&#xff0c;但是这个时候没有连接调试器&#xff0c;不好找死机原因。 下面说下在程序卡死的时候&#xff0c;在不破坏死机现场的情况下&#xff0c;连接上调试器进行程序调试的方法。 把调试器连接电脑&#xff0c;打开keil做下面的配置&#xff0c…

Llama系列上新多模态!3.2版本开源超闭源,还和Arm联手搞了手机优化版,Meta首款多模态Llama 3.2开源!1B羊驼宝宝,跑在手机上了

Llama系列上新多模态&#xff01;3.2版本开源超闭源&#xff0c;还和Arm联手搞了手机优化版&#xff0c;Meta首款多模态Llama 3.2开源&#xff01;1B羊驼宝宝&#xff0c;跑在手机上了&#xff01; 在多模态领域&#xff0c;开源模型也超闭源了&#xff01; 就在刚刚结束的Met…

Web自动化Demo-PHP+Selenium

1.新建工程 打开PhpStorm新建工程如下&#xff1a; 打开终端输入如下命令安装selenium&#xff1a; composer require php-webdriver/webdriver 2.编写代码 <?php require vendor/autoload.php;use Facebook\WebDriver\Remote\RemoteWebDriver; use Facebook\WebDriver…

分治算法(8)_归并排序_翻转对

个人主页&#xff1a;C忠实粉丝 欢迎 点赞&#x1f44d; 收藏✨ 留言✉ 加关注&#x1f493;本文由 C忠实粉丝 原创 分治算法(8)_归并排序_翻转对 收录于专栏【经典算法练习】 本专栏旨在分享学习算法的一点学习笔记&#xff0c;欢迎大家在评论区交流讨论&#x1f48c; 目录 温…

云原生日志ELK( logstash安装部署)

logstash 介绍 LogStash由JRuby语言编写&#xff0c;基于消息&#xff08;message-based&#xff09;的简单架构&#xff0c;并运行在Java虚拟机 &#xff08;JVM&#xff09;上。不同于分离的代理端&#xff08;agent&#xff09;或主机端&#xff08;server&#xff09;&…

【python】:pycharm2024.2.2使用

参考链接&#xff1a; 文件连接&#xff1a; 方法1&#xff1a;临时有效&#xff0c;后期官方更新提示激活无效 输入激活码&#xff1a; X9MQ8M5LBM-eyJsaWNlbnNlSWQiOiJYOU1ROE01TEJNIiwibGljZW5zZWVOYW1lIjoiZ3VyZ2xlcyB0dW1ibGVzIiwiYXNzaWduZWVOYW1lIjoiIiwiYXNzaWduZWVF…

Chainlit集成Dashscope实现语音交互网页对话AI应用

前言 本篇文章讲解和实战&#xff0c;如何使用Chainlit集成Dashscope实现语音交互网页对话AI应用。实现方案是对接阿里云提供的语音识别SenseVoice大模型接口和语音合成CosyVoice大模型接口使用。针对SenseVoice大模型和CosyVoice大模型&#xff0c;阿里巴巴在github提供的有开…

视频流媒体融合与视频监控汇聚管理系统集成方案

流媒体视频融合与汇聚管理系统可以实现对各类模块化服务进行统一管理和配置等操作&#xff0c;可实现对应用服务的整合、管理及共享&#xff0c;以标准接口的方式&#xff0c;业务平台及其他第三方业务平台可以方便地调用各类数据&#xff0c;具有开放性和可扩展性。在流媒体视…

opencascade鼠标拖拽框选功能

1.首先在OccView中添加用于显示矩形框的类 //! rubber rectangle for the mouse selection.Handle(AIS_RubberBand) mRectBand; 2.设置框选的属性 mRectBand new AIS_RubberBand(); //设置属性 mRectBand->SetLineType(Aspect_TOL_SOLID); //设置变宽线型为实线 mRe…

scanMiR:使用R语言预测 miRNA 结合位点

生信碱移 scanMiR 结合预测 scanMiR&#xff0c;一款R语言工具包&#xff0c;能够高效地扫描任何自定义序列上的典型和非典型miRNA结合位点&#xff0c;估计解离常数并预测聚合的转录物抑制。 最近&#xff0c;几项高通量研究试图阐明miRNA–mRNA靶向的生化决定因素。在一项发…

Unity 克隆Timeline并保留引用

Timeline的资源是.playable文件&#xff0c;简单的复制不会保留引用关系。 下面的脚本可以复制引用关系。 using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; u…

Node.js入门——fs、path模块、URL端口号、模块化导入导出、包、npm软件包管理器

Node.js入门 1.介绍 定义&#xff1a;跨平台的JS运行环境&#xff0c;使开发者可以搭建服务器端的JS应用程序作用&#xff1a;使用Node.Js编写服务器端代码Node.js是基于Chrome V8引擎进行封装&#xff0c;Node中没有BOM和DOM 2.fs模块-读写文件 定义&#xff1a;封装了与…