page74-泛型可迭代的基础集合数据类型的API-Bag+Queue+Stack
【泛型可迭代的基础集合数据类型的API】
背包:就是一种不支持从中删除元素的集合数据类型——它的目的就是帮助用例收集元素并迭代遍历所有收集到的元素。(用例也可以检查背包是否为空, 或者获取背包中元素的数量)
public class Bag<Item> implements Iterable<Item>
Bag() 创建一个空背包
void add(Item item) 添加一个元素
boolean isEmpty() 背包是否为空
int size() 背包中的元素数量
使用Bag的API, 用例可以将元素添加到背包,并通过foreach循环来访问所有元素。用例也可以使用栈或者队列, 但使用Bag可以说明元素的处理顺序不重要 。
先进先出(FIFO)队列:
public class Queue<Item> implements Iterable<Item>
Queue() 创建一个空队列
void enqueue(Item item) 添加一个元素
Item dequeue() 删除最近添加的元素
boolean isEmpty() 队列是否为空
int size() 队列中的元素数量
下压(后进先出,LIFO)栈
public class Stack<Item> implements Iterable<Item>
Stack() 创建一个空栈
void push(Item item) 添加一个元素
Item pop() 删除最近添加的元素
boolean isEmpty() 栈是否为空
int size() 栈中元素数量
Stats类是Bag的一个典型用例。
它的任务是简单地计算标准输入中的所有double值的平均值和样本标准差。数的计算顺序和结果无关,因此我们将它们保存在一个Bag对象中, 并使用foreach循环来计算每个和。
用Bag对象保存所有数字是更复杂的统计计算所必须的 。
背包的典型用例:Stats.java
public class Stats {
public static void main(String[] args) {
Bag<Double> numbers = new Bag<Double>();
while(!StdIn.isEmpty())
numbers.add(StdIn.readDouble());
int N = numbers.size();
double sum = 0.0;
for (Double x : numbers)
sum += x;
double mean = sum / N;
sum = 0.0;
for (Double x : numbers)
sum += (x-mean)*(x-mean);
double std = Math.sqrt(sum/(N-1));
StdOut.printf("mean : %.2f\n", mean);
StdOut.printf("Std dev : %.2f\n", std);
}
}
【打印结果】

【Bag.java】
import java.util.Iterator;
import java.util.NoSuchElementException; public class Bag<Item> implements Iterable<Item> { private int N; // number of elements in bag
private Node<Item> first; // beginning of bag // helper linked list class
private static class Node<Item> {//嵌套类
private Item item;
private Node<Item> next;
} /**
* Initializes an empty bag.
*/
public Bag() {
first = null;
N = 0;
} /**
* Is this bag empty?
* @return true if this bag is empty; false otherwise
*/
public boolean isEmpty() {
return first == null;
} /**
* Returns the number of items in this bag.
* @return the number of items in this bag
*/
public int size() {
return N;
} /**
* Adds the item to this bag.
* @param item the item to add to this bag
*/
public void add(Item item) {//由add()方法可以看出,是头插法。
Node<Item> oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
N++;
} /**
* Returns an iterator that iterates over the items in the bag in arbitrary order.
* @return an iterator that iterates over the items in the bag in arbitrary order
*/
public Iterator<Item> iterator() {
return new ListIterator<Item>(first);
} // an iterator, doesn't implement remove() since it's optional
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current; public ListIterator(Node<Item> first) {
current = first;
} public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); } public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
} /**
* Unit tests the <tt>Bag</tt> data type.
*/
public static void main(String[] args) {
Bag<String> bag = new Bag<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
bag.add(item);
} StdOut.println("size of bag = " + bag.size());
for (String s : bag) {
StdOut.println(s);
}
} }
【Queue.java】
import java.util.Iterator;
import java.util.NoSuchElementException; public class Queue<Item> implements Iterable<Item> {
private int N; // number of elements on queue
private Node<Item> first; // beginning of queue
private Node<Item> last; // end of queue // helper linked list class
private static class Node<Item> {
private Item item;
private Node<Item> next;
} /**
* Initializes an empty queue.
*/
public Queue() {
first = null;
last = null;
N = 0;
} /**
* Is this queue empty?
* @return true if this queue is empty; false otherwise
*/
public boolean isEmpty() {
return first == null;
} /**
* Returns the number of items in this queue.
* @return the number of items in this queue
*/
public int size() {
return N;
} /**
* Returns the item least recently added to this queue.
* @return the item least recently added to this queue
* @throws java.util.NoSuchElementException if this queue is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return first.item;
} /**
* Adds the item to this queue.
* @param item the item to add
*/
public void enqueue(Item item) {
Node<Item> oldlast = last;
last = new Node<Item>();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
N++;
} /**
* Removes and returns the item on this queue that was least recently added.
* @return the item on this queue that was least recently added
* @throws java.util.NoSuchElementException if this queue is empty
*/
public Item dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
Item item = first.item;
first = first.next;
N--;
if (isEmpty()) last = null; // to avoid loitering
return item;
} /**
* Returns a string representation of this queue.
* @return the sequence of items in FIFO order, separated by spaces
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this)
s.append(item + " ");
return s.toString();
} /**
* Returns an iterator that iterates over the items in this queue in FIFO order.
* @return an iterator that iterates over the items in this queue in FIFO order
*/
public Iterator<Item> iterator() {
return new ListIterator<Item>(first);
} // an iterator, doesn't implement remove() since it's optional
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current; public ListIterator(Node<Item> first) {
current = first;
} public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); } public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
} /**
* Unit tests the <tt>Queue</tt> data type.
*/
public static void main(String[] args) {
Queue<String> q = new Queue<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) q.enqueue(item);
else if (!q.isEmpty()) StdOut.print(q.dequeue() + " ");
}
StdOut.println("(" + q.size() + " left on queue)");
}
}
【Stack.java】
import java.util.Iterator;
import java.util.NoSuchElementException; public class Stack<Item> implements Iterable<Item> {
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() {
return new ListIterator<Item>(first);
} // an iterator, doesn't implement remove() since it's optional
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current; public ListIterator(Node<Item> first) {
current = first;
}
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); } public Item next() {
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)");
}
}
【Queue测试用例 QueueCase.java】
public class QueueCase {
public static void main(String[] args) {
int[] temp = readInts(name);
for (int i = 0; i < temp.length; i++)
System.out.println(temp[i] + " ");
}
public static int[] readInts(String name){
In in = new In(name);
Queue<Integer> q = new Queue<Integer>();
while(!in.isEmpty())
q.enqueue(in.readInt());
int N = q.size();
int[] a = new int[N];
for (int i = 0; i < N; i++)
a[i] = q.dequeue();
return a;
}
}
【Stack 测试用例 StackCase.java】
public class StackCase {
public static void main(String[] args) {
In in = new In(args[0]);
Stack<Integer> s = new Stack<Integer>();
while(!StdIn.isEmpty())
s.push(StdIn.readInt());
for (int i : s) {
System.out.println(i + " ");
}
}
}
page74-泛型可迭代的基础集合数据类型的API-Bag+Queue+Stack的更多相关文章
- 集合框架、泛型、迭代(java基础知识十六)
1.ArrayList存储自定义对象并遍历 此类的 iterator 和 listIterator 方法返回的迭代器是快速失败的:在创建迭代器之后,除非通过迭代器自身的 remove 或 add 方法 ...
- Java基础-引用数据类型之集合(Collection)
Java基础-引用数据类型之集合(Collection) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.为什么出现集合类 面向对象语言对事物的体现都是以对象的形式,所以为了方便 ...
- Java自学第6期——Collection、Map、迭代器、泛型、可变参数、集合工具类、集合数据结构、Debug
集合:集合是java中提供的一种容器,可以用来存储多个数据. 集合和数组既然都是容器,它们有啥区别呢? 数组的长度是固定的.集合的长度是可变的. 数组中存储的是同一类型的元素,可以存储基本数据类型值. ...
- Java18-java语法基础——集合框架
Java18-java语法基础——集合框架 一.什么是集合框架 1.集合框架:是为表示和操作集合而规定的一种统一的.标准的体系结构. 2.任何集合框架都包含三大块内容:对外的接口.接口的实现和对集合运 ...
- Java基础-集合的嵌套
Java基础-集合的嵌套 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.静态导入 静态导入是在JDK1.5后的新特性,可以减少开发的代码量,但是实际用处是很一般,静态导入的标准 ...
- JavaScript基础:数据类型的中的那些少见多怪
原文:JavaScript基础:数据类型的中的那些少见多怪 Javascript共有6种数据类型,其中包括3个基本数据类型(string,number,boolean).2个特殊数据类型(undefi ...
- 【python之路11】集合数据类型(set)
集合数据类型(set):集合是不重复的无需序列 1.集合数据类型的创建 a = {11,22,33} #或 a = set() #创建空集合,不能用a={},这样创建的是字典类型 2.集合转换(将可迭 ...
- Python基础之数据类型
Python基础之数据类型 变量赋值 Python中的变量不需要声明,变量的赋值操作既是变量声明和定义的过程. 每个变量在内存中创建,都包括变量的标识,名称和数据这些信息. 每个变量在使用前都必须赋值 ...
- Java基础---集合
第一讲 集合框架 先看下面的图: 这就是集合框架的构成.由于数据结构的不同,有不同的集合,也叫容器.下面是集合类的简单介绍. 一.为什么出现集合类? 面向对象语言对事物的体现都是以对象的形式,所 ...
随机推荐
- myeclipse 8.5安装freemarker插件方法
1. 下载freemarker最新版本,目前本人下载时最新版本是:freemarker-ide-0.9.14.zip, ide版本的freemarker.jar版本太低,可以替换成高级版本,并修改me ...
- GetWindowThreadProcessId用法(转)
函数功能:该函数返回创建指定窗口线程的标识和创建窗口的进程的标识符,后一项是可选的. 函数原型:DWORD GetWindowThreadProcessld(HWND hwnd,LPDWORD lpd ...
- Regular Expression--Good parts
匹配URL的正则表达式 <!doctype html><html lang="en"><head> <meta charset=" ...
- 2014年QS世界大学排名
新浪教育[微博]讯 近日2014QS世界大学排行榜发布,榜单前十强均为英美名校.其中麻省理工大学以绝对优势位居榜首:英国剑桥大学及帝国理工学院并列排名第二:哈佛大学较去年而言名次略微下降,跌至第四. ...
- Flex Builder 开发语言切换问题
1.Flex Builder 4.6切换语言 打开\Adobe\Adobe Flash Builder 4.6\FlashBuilder.ini -nlzh_CN-startupeclipse/plu ...
- Java数据结构之树和二叉树
从这里开始将要进行Java数据结构的相关讲解,Are you ready?Let's go~~ Java中的数据结构模型可以分为一下几部分: 1.线性结构 2.树形结构 3.图形或者网状结构 接下来的 ...
- 前端优化分析 之 javascript引用位置优化
在很多优化法则中都提到,尽量将javascript放到页面底部,这是为什么呢 我通过firebug进行了下简单的分析 看下图 本页面首尾都存在javascript代码 我们分析得出 1.整个页面文档 ...
- javascript 操作 excel 全攻略
最近做一个项目,用到了javascript操纵excel以生成报表,下面是标有详细注解的实例 <html> <head><script language="ja ...
- C++ Code_animateCtrl
Code:: 播放 if (!m_animate1.Open("C:\\copy.avi")) { MessageBox("NULL& ...
- iOS开发——动画编程Swift篇&(四)CABasicAnimation动画
CABasicAnimation动画 //CABasicAnimation-不透明度 @IBAction func cabOpacity() { let animation = CABasicAnim ...