理解Java中的Bag ADT:一种灵活的数据结构

本文介绍了 java 中的 bag 抽象数据类型 (adt),重点介绍了它处理具有重复元素和动态调整大小的无序集合的能力。通过详细的实现示例,它演示了 bag adt 如何提供有效的解决方案来管理库存系统等实际应用程序中的集合。

在计算机科学中,抽象数据类型(adt)对于管理和组织数据至关重要。它们可以被定义为“描述数据集以及对该数据的操作的规范”(carrano & henry,2018)。在java中,adt广泛用于包、栈、队列、集合等集合的开发。本文重点介绍 bag adt,它允许重复元素、支持动态调整大小并提供处理无序集合的灵活性。 java 中的 bag 类型是属于 collection 类的基本数据类型,见图 1。

图1
可更新集合
理解Java中的Bag ADT:一种灵活的数据结构
注意:链接缓冲区是 updatablebag 的实现,由任意数量的保存元素的缓冲区组成,排列在列表中。每个缓冲区保存一个元素数组。 arbtree 是 updatablebag 的实现,elementsortedcollection 实现红黑树,一种平衡排序二叉搜索树的形式。摘自 lee (n. d.) 的收藏包概述。

bag 的属性可以定义如下:

重复 — 允许重复。无序 — bag 元素未排序。动态调整大小 — 大小可以动态更改。可迭代——在 java 中,包是可以迭代的。无索引 — 包元素未建立索引。高效的添加操作 – 将元素添加到包中通常是 o(1) 操作。支持集合操作。见图2。通用类型——包可以容纳任何类型的元素。没有键值对 — 包存储没有关联键的元素。可变 — 包的内容在创建后可以更改,可以动态调整大小。支持空元素 – 包可能允许空元素。

图2
包类 uml
理解Java中的Bag ADT:一种灵活的数据结构
注意:来自 carrano 和 henry 的《data structures and abstractions with java》(第五版)(2018 年)。

在 java 编程语言的上下文中,堆栈、队列、

linkedlist、set 和 bag 可以描述如下:堆栈是具有特定删除顺序的元素集合的adt = lifo(后进先出),允许重复。队列是具有特定移除顺序的元素集合的adt = fifo(先进先出),允许重复。linkedlist 是列表的实现。set 是元素集合的 adt,不允许重复。bag是允许重复的元素集合的adt。

换句话说,任何包含元素的集合都是collection,任何允许重复的集合都是bag,否则就是set。 (马托尼,2017)

立即学习“Java免费学习笔记(深入)”;

bag 的主要好处是它允许重复和迭代,它也是可变的,允许动态调整其元素的大小和修改。换句话说,“如果不需要重复项,您可以使用 set 而不是 bag。此外,如果您关心删除顺序,您会选择堆栈或队列,它们基本上是具有特定删除顺序的包。您可以将 bag 视为 stack 和 queue 的超类型,它通过特定操作扩展其 api”(matoni,2017)。下面的程序是 bag adt 方法对杂货库存的简单实现的示例。

bag 类实现 bag adt

import java.util.iterator;import java.util.nosuchelementexception;/** * a simple implementation of a bag adt (abstract data type). it implements a * linked structure systems, a chain data structure. [item | next] -> [item | * next] -> [item | next] -> null. *  * @param  the type of elements held in this bag * * @author alejandro ricciardi * @date 08/12/2024 */public class bag implements iterable { private node headnode; // the first node in the bag list private int size; // number of node in the bag /**  * private inner class that creates a node in the linked structure. each node  * contains an item and a reference to the next node. [item | next] -> [item |  * next] -> [item | next] -> null  *   */ private class node {  t item; // the item stored in the node  node next; // reference to the next node } /**  * constructs an empty bag.  */ public bag() {  headnode = null; // initialize the first (head) node in the bag to null                                 (empty bag)  size = 0; // initialize size of the bag to 0 } /**  * adds the specified item to this bag. this operation runs in constant time  * o(1).  *  * @param item the item to add to the bag  */ public void add(t item) {  node nextnode = headnode; // save the current head node becoming the next                                     // node in the added node  headnode = new node(); // create a new node and make it the head node  headnode.item = item; // set the item of the new node  headnode.next = nextnode; // link the new node to the old head node  size++; // increment the size of the bag } /**  * removes one item from the bag if it exists. this operation runs in linear  * time o(n) in the worst case.  *  * @param item the item to remove  * @return true if the item was found and removed, false otherwise  */ public boolean remove(t item) {  if (headnode == null)   return false; // if the bag is empty, return false  if (headnode.item.equals(item)) { // if the item is in the first node   headnode = headnode.next; // make the next node the new head node   size--; // decrement the size   return true;  }  node current = headnode;  while (current.next != null) { // iterates the linked structure   if (current.next.item.equals(item)) { // if the next node contains                                                        // the item    current.next = current.next.next; // remove the next node from                                                        // the chain    size--; // decrement the size    return true;   }   current = current.next; // move to the next node  }  return false; // item not found in the bag } /**  * returns the number of items in this bag.  *  * @return the number of items in this bag  */ public int size() {  return size; } /**  * checks if this bag is empty.  *  * @return true if this bag contains no items, false otherwise  */ public boolean isempty() {  return size == 0; } /**  * returns an iterator that iterates over the items in this bag.  *  * @return an iterator that iterates over the items in this bag  */ public iterator iterator() {  return new bagiterator(); } /**  * private inner class that implements the iterator interface.  */ private class bagiterator implements iterator {  private node current = headnode; // start from the first (head) node  /**   * checks if there are more elements to iterate over.   *   * @return true if there are more elements, false otherwise   */  public boolean hasnext() {   return current != null;  }  /**   * returns the next element in the iteration.   *   * @return the next element in the iteration   * @throws nosuchelementexception if there are no more elements   */  public t next() {   if (!hasnext())    throw new nosuchelementexception();   t item = current.item; // get the item from the current node   current = current.next; // move to the next node   return item;  } }}

groceryinventory 使用 bag adt 方法实现了一个简单的杂货店库存管理系统

即构数智人 即构数智人

即构数智人是由即构科技推出的AI虚拟数字人视频创作平台,支持数字人形象定制、短视频创作、数字人直播等。

即构数智人 36 查看详情 即构数智人

/** * a simple grocery store inventory management system using a bag adt. *  * @author alejandro ricciardi * @date 08/12/2024  */public class groceryinventory {    // the bag adt used to store items    private bag inventory;    /**     * constructs a new grocoryinventory      */    public groceryinventory() {        inventory = new bag();    }    /**     * adds items to the inventory.     *      * @param item the name of the item to add.     * @param quantity the number of items to add.     */    public void addshipment(string item, int quantity) {        // add the item to the bag 'quantity' times        for (int i = 0; i < quantity; i++) {            inventory.add(item);        }    }    /**     * removes item from the inventory.     *      * @param item the name of the item to remove.     * @return true if the item was successfully removed, false otherwise.     */    public boolean sellitem(string item) {        return inventory.remove(item);    }    /**     * counts the number of a specific item in the inventory (duplicates).     *      * @param item the name of the item to be counted.     * @return the number of this item in the inventory.     */    public int getitemcount(string item) {        int count = 0;        // iterate through the bag and count the number of the given item in it        for (string s : inventory) {            if (s.equals(item)) {                count++;            }        }        return count;    }    /**     * main method.     */    public static void main(string[] args) {        groceryinventory store = new groceryinventory();        // add inventory        store.addshipment("apple", 50);        store.addshipment("banana", 30);        store.addshipment("orange", 40);        // initial apple count        system.out.println("apples in stock: " + store.getitemcount("apple"));        // selling apples        store.sellitem("apple");        store.sellitem("apple");        // apple count after selling        system.out.println("apples after selling 2: " +                             store.getitemcount("apple"));    }}

输出

Apples in stock: 50Apples after selling 2: 48

bag adt 在这个例子中很有用,因为它是可迭代的,它可以存储同一对象的多个实例(例如,像苹果这样的重复项),并创建一个抽象来简化对项目数据的操作,并且不需要项目待订购。与数组不同,bag 不需要固定大小,可以根据需要动态调整大小。此外,它们(对于本示例)比列表更好,因为它们不需要订购物品(例如,苹果可以存储在香蕉之后或之前)。此外,它们比 sets 更好(对于本例),因为它们允许重复(例如,您可以在商店里拥有多个苹果)。

换句话说,在这个例子中很有用并且更好,因为:

您可以轻松添加多个苹果或香蕉 (addshipment)。您可以在单个商品售出后将其移除 (sellitem)。您可以计算您拥有的每件物品的数量 (getitemcount)

总之,java 中的 bag adt 是一种灵活且高效的管理元素集合的方法,特别是在需要重复和动态调整大小时。它是一个简单但功能强大的结构,允许轻松添加、删除和迭代元素,使其成为库存系统等应用程序的理想选择,如杂货店示例所示。

参考文献:

carrano, f.m. 和 henry, t.m.(2018 年,1 月 31 日)。 java 的数据结构和抽象(第五版)。皮尔逊。

lee, d. (n. d.)。收藏包概述 [doug lea 的主页]。纽约州立大学计算机科学系。 https://gee.cs.oswego.edu/dl/classes/collections/

马托尼(2017 年,4 月 15 日)。在 java 中使用 bag 的原因 [post]。堆栈溢出。 https://stackoverflow.com/questions/43428114/reasons-for-using-a-bag-in-java

最初于 2024 年 10 月 3 日发表于 alex.omegapy – medium。

以上就是理解Java中的Bag ADT:一种灵活的数据结构的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/614409.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
探探解除匹配怎么做_探探取消与对方匹配关系指南
上一篇 2025年11月11日 03:11:06
下一篇 2025年11月11日 03:11:15

相关推荐

  • 开源免费PHP工具 PHP开发效率提升利器

    推荐开源免费PHP开发工具以提升效率:VS Code、Sublime Text轻量高效,PhpStorm专业强大;调试用Xdebug、Kint、Ray;依赖管理选Composer;代码质量工具包括PHPStan、Psalm、PHP_CodeSniffer;数据库管理可用%ignore_a_1%MyA…

    2026年5月10日
    000
  • Golang JSON序列化:控制敏感字段暴露的最佳实践

    本教程探讨golang中如何高效控制结构体字段在json序列化时的可见性。当需要将包含敏感信息的结构体数组转换为json响应时,通过利用`encoding/json`包提供的结构体标签,特别是`json:”-“`,可以轻松实现对特定字段的忽略,从而避免敏感数据泄露,确保api…

    2026年5月10日
    000
  • 比特币新手教程 比特币交易平台有哪些

    比特币是一种去中心化的数字货币,基于区块链技术实现点对点交易,具有匿名性、有限发行和不可篡改等特点;新手可通过交易所购买,P2P交易获得比特币,常用平台包括Binance、OKX和Huobi;交易流程包括注册账户、实名认证、绑定支付方式、充值法币并下单购买,可选择市价单或限价单;比特币存储方式有交易…

    2026年5月10日
    000
  • c++中的SFINAE技术是什么_c++模板编程中的SFINAE原理与应用

    SFINAE 是“替换失败不是错误”的原则,指模板实例化时若参数替换导致错误,只要存在其他合法候选,编译器不报错而是继续重载决议。它用于条件启用模板、类型检测等场景,如通过 decltype 或 enable_if 控制函数重载,实现类型特征判断。尽管 C++20 引入 Concepts 简化了部分…

    2026年5月10日
    000
  • Go语言mgo查询构建:深入理解bson.M与日期范围查询的正确实践

    本文旨在解决go语言mgo库中构建复杂查询时,特别是涉及嵌套`bson.m`和日期范围筛选的常见错误。我们将深入剖析`bson.m`的类型特性,解释为何直接索引`interface{}`会导致“invalid operation”错误,并提供一种推荐的、结构清晰的代码重构方案,以确保查询条件能够正确…

    2026年5月10日
    100
  • Golang goroutine与channel调试技巧

    使用go run -race检测数据竞争,结合runtime.NumGoroutine监控协程数量,通过pprof分析阻塞调用栈,利用select超时避免永久阻塞,有效排查goroutine泄漏、死锁和数据竞争问题。 Go语言的goroutine和channel是并发编程的核心,但它们也带来了调试上…

    2026年5月10日
    000
  • 使用 Jupyter Notebook 进行探索性数据分析

    Jupyter Notebook通过单元格实现代码与Markdown结合,支持数据导入(pandas)、清洗(fillna)、探索(matplotlib/seaborn可视化)、统计分析(describe/corr)和特征工程,便于记录与分享分析过程。 Jupyter Notebook 是进行探索性…

    2026年5月10日
    000
  • 《魔兽世界》将于6月11日开启国服回归技术测试

    《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试

    《%ign%ignore_a_1%re_a_1%》官方宣布,将于6月11日开启国服回归技术测试,时间为7天,并称可以在6月内正式开服,玩家们可以访问官网下载战网客户端并预下载“巫妖王之怒”客户端,技术测试详情见下图。 WordAi WordAI是一个AI驱动的内容重写平台 53 查看详情 以上就是《…

    2026年5月10日 用户投稿
    200
  • 如何在HTML中插入表单元素_HTML表单控件与输入类型使用指南

    HTML表单通过标签构建,包含action和method属性定义数据提交目标与方式,常用input类型如text、password、email等适配不同输入需求,配合label、required、placeholder提升可用性,结合textarea、select、button等控件实现完整交互,是…

    2026年5月10日
    100
  • 创建指定大小并填充特定数据的Golang文件教程

    本文将介绍如何使用Golang创建一个指定大小的文件,并用特定数据填充它。我们将使用 `os` 包提供的函数来创建和截断文件,从而实现快速生成大文件的目的。示例代码展示了如何创建一个10MB的文件,并将其填充为全零数据。掌握这些方法,可以方便地在例如日志系统或磁盘队列等场景中,预先创建测试文件或初始…

    2026年5月10日
    000
  • Python命令怎样使用profile分析脚本性能 Python命令性能分析的基础教程

    使用Python的cProfile模块分析脚本性能最直接的方式是通过命令行执行python -m cProfile your_script.py,它会输出每个函数的调用次数、总耗时、累积耗时等关键指标,帮助定位性能瓶颈;为进一步分析,可将结果保存为文件python -m cProfile -o ou…

    2026年5月10日
    000
  • 如何插入查询结果数据_SQL插入Select查询结果方法

    如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法

    使用INSERT INTO…SELECT语句可高效插入数据,通过NOT EXISTS、LEFT JOIN、MERGE语句或唯一约束避免重复;表结构不一致时可通过别名、类型转换、默认值或计算字段处理;结合存储过程可提升可维护性,支持参数化与动态SQL。 将查询结果数据插入到另一个表中,可以…

    2026年5月10日 用户投稿
    000
  • 使用 WebCodecs VideoDecoder 实现精确逐帧回退

    本文档旨在解决在使用 WebCodecs VideoDecoder 进行视频解码时,实现精确逐帧回退的问题。通过比较帧的时间戳与目标帧的时间戳,可以避免渲染中间帧,从而提高用户体验。本文将提供详细的解决方案和示例代码,帮助开发者实现精确的视频帧控制。 在使用 WebCodecs VideoDecod…

    2026年5月10日
    000
  • Debian Copilot的社区活跃度如何

    debian copilot是codeberg社区维护的ai助手,旨在为debian用户提供服务。尽管搜索结果中没有直接提供关于debian copilot社区支持活跃度的具体数据,但我们可以通过debian社区的整体活跃度和特点来推断其活跃性。 Debian社区的一般情况: Debian拥有详尽的…

    2026年5月10日
    000
  • Discord.py 交互按钮超时与持久化解决方案

    本教程旨在解决Discord.py中交互按钮在一段时间后出现“This Interaction Failed”错误的问题。我们将深入探讨视图(View)的超时机制,并提供通过正确设置timeout参数以及利用bot.add_view()方法实现按钮持久化的具体方案,确保您的机器人交互功能稳定可靠,即…

    2026年5月10日
    000
  • Python递归函数追踪与性能考量:以序列打印为例

    本文深入探讨了Python中一种递归打印序列元素的方法,并着重演示了如何通过引入缩进参数来有效追踪递归函数的执行流程和参数变化。通过实际代码示例,文章揭示了递归调用可能带来的潜在性能开销,特别是对调用栈空间的需求,以及Python默认递归深度限制可能导致的错误,为读者提供了理解和优化递归算法的实用见…

    2026年5月10日
    000
  • JavaScript 动态菜单点击高亮效果实现教程

    本教程详细介绍了如何使用 JavaScript 实现动态菜单的点击高亮功能。通过事件委托和状态管理,当用户点击菜单项时,被点击项会高亮显示(绿色),同时其他菜单项恢复默认样式(白色)。这种方法避免了不必要的DOM操作,提高了性能和代码可维护性,确保了无论点击方向如何,功能都能稳定运行。 动态菜单高亮…

    2026年5月10日
    200
  • c++如何实现UDP通信_c++基于UDP的网络通信示例

    UDP通信基于套接字实现,适用于实时性要求高的场景。1. 流程包括创建套接字、绑定地址(接收方)、发送(sendto)与接收(recvfrom)数据、关闭套接字;2. 服务端监听指定端口,接收客户端消息并回传;3. 客户端发送消息至服务端并接收响应;4. 跨平台需处理Winsock初始化与库链接,编…

    2026年5月10日
    100
  • 谷歌浏览器如何截图 谷歌浏览器页面截图技巧

    谷歌浏览器如何截图 谷歌浏览器页面截图技巧谷歌浏览器如何截图 谷歌浏览器页面截图技巧谷歌浏览器如何截图 谷歌浏览器页面截图技巧谷歌浏览器如何截图 谷歌浏览器页面截图技巧

    使用谷歌浏览器的开发者工具截图步骤:1. 按ctrl+shift+i(windows/linux)或cmd+option+i(mac)打开开发者工具。2. 点击右上角三个点,选择”更多工具”,再选择”截图”。3. 选择截取整个页面。推荐的谷歌浏览器扩展…

    2026年5月10日 用户投稿
    100
  • JavaScript函数中插入加载动画(Spinner)的正确方法

    本文旨在解决在JavaScript函数中插入加载动画(Spinner)时遇到的异步问题。通过引入async/await和Promise.all,确保在数据处理完成前后正确显示和隐藏加载动画,提升用户体验。我们将提供两种实现方案,并详细解释其原理和优势。 在Web开发中,当执行耗时操作时,显示加载动画…

    2026年5月10日
    100

发表回复

登录后才能评论
关注微信