理解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:07:25
下一篇 2025年11月11日 03:11:18

相关推荐

  • 如何利用BFC和inline-block解决兄弟元素间margin塌陷问题?

    BFC清除兄弟元素间margin塌陷原理 margin塌陷问题 当相邻的块级元素垂直排列,它们的margin可能会塌陷并重叠,称为margin塌陷。 BFC清除margin塌陷 清除margin塌陷的一种常见方法是将下方元素包裹在一个新的块级格式化上下文(BFC)中,因为BFC之间不会相互影响。 d…

    2025年12月24日
    500
  • Uniapp 中如何不拉伸不裁剪地展示图片?

    灵活展示图片:如何不拉伸不裁剪 在界面设计中,常常需要以原尺寸展示用户上传的图片。本文将介绍一种在 uniapp 框架中实现该功能的简单方法。 对于不同尺寸的图片,可以采用以下处理方式: 极端宽高比:撑满屏幕宽度或高度,再等比缩放居中。非极端宽高比:居中显示,若能撑满则撑满。 然而,如果需要不拉伸不…

    2025年12月24日
    400
  • 如何让小说网站控制台显示乱码,同时网页内容正常显示?

    如何在不影响用户界面的情况下实现控制台乱码? 当在小说网站上下载小说时,大家可能会遇到一个问题:网站上的文本在网页内正常显示,但是在控制台中却是乱码。如何实现此类操作,从而在不影响用户界面(UI)的情况下保持控制台乱码呢? 答案在于使用自定义字体。网站可以通过在服务器端配置自定义字体,并通过在客户端…

    2025年12月24日
    800
  • 如何优化CSS Grid布局中子元素排列和宽度问题?

    css grid布局中的优化问题 在使用css grid布局时可能会遇到以下问题: 问题1:无法控制box1中li的布局 box1设置了grid-template-columns: repeat(auto-fill, 20%),这意味着容器将自动填充尽可能多的20%宽度的列。当li数量大于5时,它们…

    2025年12月24日
    800
  • 如何在地图上轻松创建气泡信息框?

    地图上气泡信息框的巧妙生成 地图上气泡信息框是一种常用的交互功能,它简便易用,能够为用户提供额外信息。本文将探讨如何借助地图库的功能轻松创建这一功能。 利用地图库的原生功能 大多数地图库,如高德地图,都提供了现成的信息窗体和右键菜单功能。这些功能可以通过以下途径实现: 高德地图 JS API 参考文…

    2025年12月24日
    400
  • 如何使用 scroll-behavior 属性实现元素scrollLeft变化时的平滑动画?

    如何实现元素scrollleft变化时的平滑动画效果? 在许多网页应用中,滚动容器的水平滚动条(scrollleft)需要频繁使用。为了让滚动动作更加自然,你希望给scrollleft的变化添加动画效果。 解决方案:scroll-behavior 属性 要实现scrollleft变化时的平滑动画效果…

    2025年12月24日
    000
  • 如何为滚动元素添加平滑过渡,使滚动条滑动时更自然流畅?

    给滚动元素平滑过渡 如何在滚动条属性(scrollleft)发生改变时为元素添加平滑的过渡效果? 解决方案:scroll-behavior 属性 为滚动容器设置 scroll-behavior 属性可以实现平滑滚动。 html 代码: click the button to slide right!…

    2025年12月24日
    500
  • 为什么设置 `overflow: hidden` 会导致 `inline-block` 元素错位?

    overflow 导致 inline-block 元素错位解析 当多个 inline-block 元素并列排列时,可能会出现错位显示的问题。这通常是由于其中一个元素设置了 overflow 属性引起的。 问题现象 在不设置 overflow 属性时,元素按预期显示在同一水平线上: 不设置 overf…

    2025年12月24日 好文分享
    400
  • 如何选择元素个数不固定的指定类名子元素?

    灵活选择元素个数不固定的指定类名子元素 在网页布局中,有时需要选择特定类名的子元素,但这些元素的数量并不固定。例如,下面这段 html 代码中,activebar 和 item 元素的数量均不固定: *n *n 如果需要选择第一个 item元素,可以使用 css 选择器 :nth-child()。该…

    2025年12月24日
    200
  • 使用 SVG 如何实现自定义宽度、间距和半径的虚线边框?

    使用 svg 实现自定义虚线边框 如何实现一个具有自定义宽度、间距和半径的虚线边框是一个常见的前端开发问题。传统的解决方案通常涉及使用 border-image 引入切片图片,但是这种方法存在引入外部资源、性能低下的缺点。 为了避免上述问题,可以使用 svg(可缩放矢量图形)来创建纯代码实现。一种方…

    2025年12月24日
    100
  • 面板翻页显示16张图片和信息,如何实现模块靠左显示并按行排列?

    如何在面板上翻页显示16个图片和信息,如何设置div内的模块靠左显示,模块内容按行显示? 问题:在面板上翻页显示16个图片和信息,如何设置div内的模块靠左显示,模块内容按行显示,设置了float没有效果。 已知信息: 图片和信息使用json数据定义。使用paginationbyjs函数进行分页。使…

    2025年12月24日
    000
  • 如何在面板上翻页显示16个图片和信息,并实现模块靠左显示、内容按行排列?

    如何设置div内的模块靠左显示,模块内容按行显示? 问题: 在面板上翻页显示16个图片和信息,如何设置div内的模块靠左显示,模块内容按行显示,设置了float没有效果。 答案: 要将div内的模块靠左显示,并按行排列模块内容,可以使用以下方式: 给div容器添加flexbox属性: #list {…

    2025年12月24日
    000
  • 如何实现 div 内模块靠左显示并按行排列, 且翻页显示图片和信息?

    如何设置div内的模块靠左显示,模块内容按行显示? 在面板上翻页显示16个图片和信息,如何设置div内的模块靠左显示,模块内容按行显示,设置了float没有效果 中间部分里面的图片,文字显示在图片下方 第二页图片靠左显示 以上就是如何实现 div 内模块靠左显示并按行排列, 且翻页显示图片和信息?的…

    2025年12月24日
    000
  • 微信小程序文本省略后如何避免背景色溢出?

    去掉单行文本溢出多余背景色 在编写微信小程序时,如果希望文本超出宽度后省略显示并在末尾显示省略号,但同时还需要文本带有背景色,可能会遇到如下问题:文本末尾出现多余的背景色块。这是因为文本本身超出部分被省略并用省略号代替,但其背景色依然存在。 要解决这个问题,可以采用以下方法: 给 text 元素添加…

    2025年12月24日
    000
  • 如何让“元素跟随文本高度,而不是撑高父容器?

    如何让 元素跟随文本高度,而不是撑高父容器 在页面布局中,经常遇到父容器高度被子元素撑开的问题。在图例所示的案例中,父容器被较高的图片撑开,而文本的高度没有被考虑。本问答将提供纯css解决方案,让图片跟随文本高度,确保父容器的高度不会被图片影响。 解决方法 为了解决这个问题,需要将图片从文档流中脱离…

    2025年12月24日
    000
  • Flex 布局左右同高怎么实现?

    flex布局左右同高 在flex布局中,左右布局的元素高度不一致时,想要让边框延伸到最大高度,可以采用以下方法: 基于当前结构的方法: 给.rht和.lft盒子添加: .rht { height: min-content;} 这样可以使弹性盒子被子盒子内容撑开。 使用javascript获取.rht…

    2025年12月24日
    000
  • inline-block元素错位了,是为什么?

    inline-block元素错位背后的原因 inline-block元素是一种特殊类型的块级元素,它可以与其他元素行内排列。但是,在某些情况下,inline-block元素可能会出现错位显示的问题。 错位的原因 当inline-block元素设置了overflow:hidden属性时,它会影响元素的…

    2025年12月24日
    000
  • 为什么 CSS mask 属性未请求指定图片?

    解决 css mask 属性未请求图片的问题 在使用 css mask 属性时,指定了图片地址,但网络面板显示未请求获取该图片,这可能是由于浏览器兼容性问题造成的。 问题 如下代码所示: 立即学习“前端免费学习笔记(深入)”; icon [data-icon=”cloud”] { –icon-cl…

    2025年12月24日
    200
  • 为什么使用 inline-block 元素时会错位?

    inline-block 元素错位成因剖析 在使用 inline-block 元素时,可能会遇到它们错位显示的问题。如代码 demo 所示,当设置了 overflow 属性时,a 标签就会错位下沉,而未设置时却不会。 问题根源: overflow:hidden 属性影响了 inline-block …

    2025年12月24日
    000
  • 如何去除带有背景色的文本单行溢出时的多余背景色?

    带背景色的文字单行溢出处理:去除多余的背景色 当一个带有背景色的文本因单行溢出而被省略时,可能会出现最后一个背景色块多余的情况。针对这种情况,可以通过以下方式进行处理: 在示例代码中,问题在于当文本溢出时,overflow: hidden 属性会导致所有文本元素(包括最后一个)都隐藏。为了解决该问题…

    2025年12月24日
    000

发表回复

登录后才能评论
关注微信