Java Iterable interface[Algorithm]

【信息科学与工程学】【产品体系】【数据中心】第四十四篇 云资源部署设计04 设计基于SD-WAN的多云互联方案,通过软件定义的overlay网络连接阿里云、AWS、腾讯云、华为云等,实现动态路径选择和带宽聚合,替代传统MPLS VPN。- 综合评分函数:Scorei​=w1​⋅Li​Lmin​​+w2​⋅(1−Pi​)+w3​⋅Bmax​Bi​​−w4​⋅Cmax​Ci​​。设计基于eBPF/XDP的容器网络加速方案,替换传统的iptables/kube-proxy,实现Pod间通信零拷贝转发,降低延迟和CPU开销。 阅读详情

Q:什么是Iterable接口?

A:只有一个方法,放回Iterator,如下:

public interface Iterable<Item>
{
     Iterator<Item> iterator();
}


Q:什么是Iterator接口?

A:有两个方法:hasNext()和next()。第三个方法: remove()可选

Q:为什么要用数据结构Iterable?

A:Java支持优雅的客户代码,应用场景如下:

for (String s : stack)
    System.out.println(s);
Iterator<String> i = stack.iterator(); 
while (i.hasNext())
{
     String s = i.next();
     System.out.println(s);
}

下面,以Stack类实现Iterable为例,介绍Iterable的实现方法:

/*************************************************************************
 *  Compilation:  javac Stack.java
 *  Execution:    java Stack < input.txt
 *
 *  A generic stack, implemented using a singly-linked list.
 *  Each stack element is of type Item.
 *
 *  This version uses a static nested class Node (to save 8 bytes per
 *  Node), whereas the version in the textbook uses a non-static nested
 *  class (for simplicity).
 *  
 *  % more tobe.txt 
 *  to be or not to - be - - that - - - is
 *
 *  % java Stack < tobe.txt
 *  to be not that or be (2 left on stack)
 *
 *************************************************************************/

import java.util.Iterator;
import java.util.NoSuchElementException;


/**
 *  The <tt>Stack</tt> class represents a last-in-first-out (LIFO) stack of generic items.
 *  It supports the usual <em>push</em> and <em>pop</em> operations, along with methods
 *  for peeking at the top item, testing if the stack is empty, and iterating through
 *  the items in LIFO order.
 *  <p>
 *  This implementation uses a singly-linked list with a static nested class for
 *  linked-list nodes. See {@link LinkedStack} for the version from the
 *  textbook that uses a non-static nested class.
 *  The <em>push</em>, <em>pop</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>
 *  operations all take constant time in the worst case.
 *  <p>
 *  For additional documentation, see <a href="/algs4/13stacks">Section 1.3</a> of
 *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
 *
 *  @author Robert Sedgewick
 *  @author Kevin Wayne
 */
public class Stack<Item> implements Iterable<Item> {<span style="color:#ff0000;">//声明,实现Iterable接口</span>
    private int N;                // size of the stack
    private Node<Item> first;     // top of stack

    // helper linked list class
    private static class Node<Item> {
        private Item item;
        private Node<Item> next;
    }

    /**
     * Initializes an empty stack.
     */
    public Stack() {
        first = null;
        N = 0;
    }

    /**
     * Is this stack empty?
     * @return true if this stack is empty; false otherwise
     */
    public boolean isEmpty() {
        return first == null;
    }

    /**
     * Returns the number of items in the stack.
     * @return the number of items in the stack
     */
    public int size() {
        return N;
    }

    /**
     * Adds the item to this stack.
     * @param item the item to add
     */
    public void push(Item item) {
        Node<Item> oldfirst = first;
        first = new Node<Item>();
        first.item = item;
        first.next = oldfirst;
        N++;
    }

    /**
     * Removes and returns the item most recently added to this stack.
     * @return the item most recently added
     * @throws java.util.NoSuchElementException if this stack is empty
     */
    public Item pop() {
        if (isEmpty()) throw new NoSuchElementException("Stack underflow");
        Item item = first.item;        // save item to return
        first = first.next;            // delete first node
        N--;
        return item;                   // return the saved item
    }


    /**
     * Returns (but does not remove) the item most recently added to this stack.
     * @return the item most recently added to this stack
     * @throws java.util.NoSuchElementException if this stack is empty
     */
    public Item peek() {
        if (isEmpty()) throw new NoSuchElementException("Stack underflow");
        return first.item;
    }

    /**
     * Returns a string representation of this stack.
     * @return the sequence of items in the stack in LIFO order, separated by spaces
     */
    public String toString() {
        StringBuilder s = new StringBuilder();
        for (Item item : this)
            s.append(item + " ");
        return s.toString();
    }
       

    /**
     * Returns an iterator to this stack that iterates through the items in LIFO order.
     * @return an iterator to this stack that iterates through the items in LIFO order.
     */
    public Iterator<Item> iterator() {<span style="color:#ff0000;">//实现iterator方法,返回Iterator</span>
        return new ListIterator<Item>(first);
    }

    // an iterator, doesn't implement remove() since it's optional
    private class ListIterator<Item> implements Iterator<Item> {<span style="color:#ff0000;">//实现Iterator</span>
        private Node<Item> current;

        public ListIterator(Node<Item> first) {
            current = first;
        }
        public boolean hasNext()  { return current != null;                     }<span style="color:#ff0000;">//实现hasNext方法</span>
        public void remove()      { throw new UnsupportedOperationException();  }//remove方法可选

        public Item next() {<span style="color:#ff0000;">//实现next方法</span>
            if (!hasNext()) throw new NoSuchElementException();
            Item item = current.item;
            current = current.next; 
            return item;
        }
    }


    /**
     * Unit tests the <tt>Stack</tt> data type.
     */
    public static void main(String[] args) {
        Stack<String> s = new Stack<String>();
        while (!StdIn.isEmpty()) {
            String item = StdIn.readString();
            if (!item.equals("-")) s.push(item);
            else if (!s.isEmpty()) StdOut.print(s.pop() + " ");
        }
        StdOut.println("(" + s.size() + " left on stack)");
    }
}



[记录一个bug]av_hwdevice_ctx_create出现Cannot allocate memory(附带库运行时路径)[已解决] 新写的程序里调用ffmpeg的av_hwdevice_ctx_create()这个函数,出现Cannot allocate memory。但是另个程序一样的代码,居然是成功的。 反复检查之后无果,就跳出去查了一下,看到一个问答: Have you tried to use ffmpg executables with the same libs that you using when you run the app? Have you tried to use ffmpg executables 阅读详情

相关推荐

Playwright与MCP协议结合:AI驱动的智能Web自动化测试实践

Web自动化测试是现代软件开发流程中保障产品质量的关键环节,其核心原理是通过程序模拟用户操作,对Web应用进行功能验证。传统自动化测试工具如Selenium和Playwright虽然提供了强大的API,但脚本编写和维护仍需较高的编程技能。随着AI技术的发展,智能测试成为新的趋势,它通过自然语言理解和自动化执行,显著降低了测试创建门槛。Model Context Protocol(MCP)作为一种连接AI模型与外部工具的开放协议,为自动化测试带来了“智能大脑”。通过将MCP与Playwright结合,测试人员

aoe41606的博客 604

Java集合(1)——Iterable接口和Iterator接口

集合类图 Iterable 是Java.lang包下的接口 Iterabtor是java.util包下的接口 Iterable接口包装了Iterator接口 java.lang.Iterable接口 官方文档介绍: Implementing this interface allows an object to be the target of the “for-eac...

想当厨子的程序媛 599

R语言:基于Spatstat包的单变量和双变量平面Ripley‘s K函数分析

因为网上查找得到的R语言K函数分析的资料很少,Spatstat包的介绍也很少,所以抛砖引玉。本文简单介绍了使用R语言spatstat包的Kest,Kcross(Lcross)和Kinhom方法进行了单变量和双变量平面Ripley's K函数分析的方法及代码,希望有所帮助。

hsdcmax的博客 1万+

Iterable接口

第1部分 Iterable介绍

彬 3858

线性模型:AR、MA、ARMA、ARMAX、ARX、ARARMAX、OE、BJ等

线性模型:AR、MA、ARMA、ARMAX、ARX、ARARMAX、OE、BJ等

zephyr_wang的博客 1万+

头歌 操作系统 课堂练习2.1:外部中断 第2关:第一次时钟中断

将答案0x796c输入到workspace/mushixun/恢复点的地址.txt中的括号里即可,随后使用kill命令防止对第三关的环境造成影响。

Yinfrey的博客 6085

实现接口 Interface Iterable<T>

实现接口 Interface IterableJava Doc完整代码 Java Doc public interface Iterable Implementing this interface allows an object to be the target of the enhanced for statement (sometimes called the “for-each loop”...

FFXY 9万+

手把手教你学Simulink——高频隔离型双向DC-AC逆变器的建模与仿真

本文系统讲解高频隔离型双向DC-AC逆变器的Simulink建模与仿真,基于DAB+全桥逆变两级拓扑,详述DAB移相控制原理、双闭环控制策略及分步仿真搭建流程。重点涵盖电路建模、控制环设计、参数设置与常见问题调试,强调模块化分步验证与分层控制逻辑,实现安全、高效、灵活的双向能量流动仿真,适用于储能、微电网等场景的系统开发与验证。

MHD0815的博客 107

Iterable 接口解析

Iterable<T> 接口解析 一、说明 源码中是这样解释的:Implementing this interface allows an object to be the target of the “for-each loop” statement. See For-each Loop(实现此接口允许对象成为“ for-each循环”语句的目标。 请参阅 《For-each Loo...

TEXOUS的博客 2782

Docker 环境 Playwright MCP 部署全流程指南

Docker部署Playwright MCP全流程指南 本文详细介绍了使用Docker容器化部署Playwright MCP的完整流程,涵盖镜像拉取、容器启动、配置优化和问题排查。主要内容包括: 核心部署步骤:通过官方镜像快速搭建环境,支持自定义端口和数据持久化 关键配置要点:详解网络设置、持久化目录挂载和环境变量配置 服务验证方法:通过日志检查和服务连通性测试确保部署成功 客户端集成:提供VS Code等IDE的配置示例 常见问题解决:针对浏览器启动超时、跨域限制等问题给出解决方案 实战案例:演示自动化爬

勤奋的码农 1473

事件驱动的 SAP 工作流:从 BOR 事件到 Event Linkage 的落地与排障全景图

摘要: SAP工作流中的Event是业务对象状态变化的系统广播机制,如发票录入、采购订单释放等事件。通过事件驱动,业务程序与流程引擎解耦,业务只需发布事件,流程引擎负责后续处理。文章详细解析了SAP工作流事件的完整链路,包括事件定义、触发机制、事件容器传递、SWE2配置的关键作用,以及事件不触发时的排查方法。重点介绍了事件在启动流程、终止任务、等待步骤和主动创建中的应用,并结合采购订单审批案例说明事件的实际使用场景和配置要点。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 188

Java中Iterable和Iterator的辨析

本文主要对Iterable和Iterator两个接口进行深入学习。1、Iterable接口Iterable接口 (java.lang.Iterable) 是Java集合的顶级接口之一。我们首先看下这这个接口在JDK中的定义:package java.lang; public interface Iterable<AnyType> { Iterator<AnyType> iterator(

TangowL 1万+

cesium加载geotiff的 四种方法

本文介绍了在Cesium中加载GeoTIFF数据的两种主要方法。首先解析了核心前置知识,包括坐标系匹配、数据类型区分和性能优化。方法1详细演示了如何将RGB影像GeoTIFF转换为Cesium影像图层,包含从数据解析到Canvas转换的完整代码流程。方法2则针对高程数据(DEM)处理,展示了前端直接解析构建地形网格的方案。文章提供了完整的代码示例和关键实现要点,适用于卫星影像、专题图和数字高程模型等多种GeoTIFF数据类型在三维场景中的可视化需求。

大剑师兰特的GIS世界 394

【Java】Iterable接口的使用

这里写目录标题写法1:for循环写法2:foreach循环写法3:Iterator查看源码你知道Iterable默认指针指的的第一个对象还是,指针变量呢?看完下面这个你或许就知道了第二个例子代码: 定义:为对象使用迭代器iterator提供统一调用。 接口中的函数: 获取迭代器对象:iterator(); 对Iterable的每个元素执行给定操作action:forEach(Consumer<? super T> action) 在Iterable描述的元素上创建Spliterator:sp

haoweixl的博客 1万+

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

[java学习笔记]Iterator和Iterable接口

Iterator和Iterable都是java的迭代器接口,二者既有区别又有联系,下面从接口定义,接口调用和实际应用三方面具体分析这两个接口。

cifer的学习笔记 1466

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

树状形式打印二叉树

树状结构打印二叉树,na

Hooting的码农笔记本 1万+

ajax发送get、post请求

ajax可以发送post或者get请求,并且keyi

Hooting的码农笔记本 1万+

字符输出大小不一致的问题

在例如JTextArea这样的kongjian

Hooting的码农笔记本 1万+

Eclipse + Tomcat 配置

开发环境 Eclipse For Java EE(Kepler Release) Tomcat(7.0) 开发步骤 点击Eclipse->Help->Install New Software.. 添加更新源:http://download.eclipse.org/callisto/releases/ 选中Web and J2EE Development并安装 新建

Hooting的码农笔记本 9722

JDK配置

Window7下的JDK环境变量配置:

Hooting的码农笔记本 9511

判断字符串是否能分割成字典中的单词(一)——Leetcode系列(十一)

Word Break Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s = "leetco

Hooting的码农笔记本 4260

判断字符串是否能分割成字典中的单词(二)——Leetcode系列(十二)

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. For example, given s = "

Hooting的码农笔记本 3527

Java HashMap的实现

HashMap是Java中经常使用的集合类。

Hooting的码农笔记本 3267

Iterator与Enumeration的区别

Iterator是一个接口,包含三个方法: hasNext() next() remove() Enumeration也是一个接口,它是一个遗留类,集合类中只有Vector和HashTable实现了该接口。它包含了两个方法: 1. hasMoreElements() 2. nextElement()由接口定义可知,Iterator在遍历时可以对元素进行删除操作,当遍历过程中,有其他线程对集合类的

Hooting的码农笔记本 2939

使用快速排序算法对列表进行排序——Leetcode系列(四)

Sort a linked list in O(n log n) time using constant space complexity. My Answer:

Hooting的码农笔记本 2929

Quick-Union[Algorithm]

Q. Is there a path connecting p and q ?

Hooting的码农笔记本 2894
上一篇: Search a 2D Matrix ——Leetcode系列(十八)
下一篇: Java HashMap的实现
Hooting
博客等级 码龄17年 11粉丝 44原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值