ThinkJava-持有对象
- package com.cy.container;
- import java.util.*;
- public class AddingGroups {
- public static void main(String[] args) {
- Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));
- Integer[] moreInts = { 6, 7, 8, 9, 10 };
- collection.addAll(Arrays.asList(moreInts));
- Collections.addAll(collection, 11,12,13,14,15);
- Collections.addAll(collection, moreInts);
- System.out.println(collection);
- // Produces a list "backed by" an array:
- List<Integer> list = Arrays.asList(16, 17, 18, 19, 20);
- list.set(1, 99); // OK -- modify an element
- list.add(21); // Runtime error because the underlying array cannot be resized.
- }
- }
打印:
- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 6, 7, 8, 9, 10]
- Exception in thread "main" java.lang.UnsupportedOperationException
- at java.util.AbstractList.add(AbstractList.java:148)
- at java.util.AbstractList.add(AbstractList.java:108)
- at com.cy.container.AddingGroups.main(AddingGroups.java:19)
- package com.cy.container;
- //: holding/PrintingContainers.java
- // Containers print themselves automatically.
- import java.util.*;
- import static com.java.util.Print.*;
- public class PrintingContainers {
- static Collection fill(Collection<String> collection) {
- collection.add("rat");
- collection.add("cat");
- collection.add("dog");
- collection.add("dog");
- return collection;
- }
- static Map fill(Map<String,String> map) {
- map.put("rat", "Fuzzy");
- map.put("cat", "Rags");
- map.put("dog", "Bosco");
- map.put("dog", "Spot");
- return map;
- }
- public static void main(String[] args) {
- print(fill(new ArrayList<String>()));
- print(fill(new LinkedList<String>()));
- print(fill(new HashSet<String>()));
- print(fill(new TreeSet<String>()));
- print(fill(new LinkedHashSet<String>()));
- print(fill(new HashMap<String,String>()));
- print(fill(new TreeMap<String,String>()));
- print(fill(new LinkedHashMap<String,String>()));
- }
- } /* Output:
- [rat, cat, dog, dog]
- [rat, cat, dog, dog]
- [dog, cat, rat]
- [cat, dog, rat]
- [rat, cat, dog]
- {dog=Spot, cat=Rags, rat=Fuzzy}
- {cat=Rags, dog=Spot, rat=Fuzzy}
- {rat=Fuzzy, cat=Rags, dog=Spot}
- *///:~
- package com.cy.container;
- //: holding/ListIteration.java
- import typeinfo.pets.*;
- import java.util.*;
- public class ListIteration {
- public static void main(String[] args) {
- List<Pet> pets = Pets.arrayList(8);
- ListIterator<Pet> it = pets.listIterator();
- while(it.hasNext())
- System.out.print(it.next() + ", " + it.nextIndex() +
- ", " + it.previousIndex() + "; ");
- System.out.println();
- // Backwards:
- while(it.hasPrevious())
- System.out.print(it.previous().id() + " ");
- System.out.println();
- System.out.println(pets);
- it = pets.listIterator(3);
- while(it.hasNext()) {
- it.next();
- it.set(Pets.randomPet());
- }
- System.out.println(pets);
- }
- }
- /* Output:
- Rat, 1, 0; Manx, 2, 1; Cymric, 3, 2; Mutt, 4, 3; Pug, 5, 4; Cymric, 6, 5; Pug, 7, 6; Manx, 8, 7;
- 7 6 5 4 3 2 1 0
- [Rat, Manx, Cymric, Mutt, Pug, Cymric, Pug, Manx]
- [Rat, Manx, Cymric, Cymric, Rat, EgyptianMau, Hamster, EgyptianMau]
- *///:~
- package com.cy.container;
- //: holding/LinkedListFeatures.java
- import typeinfo.pets.*;
- import java.util.*;
- import static com.java.util.Print.*;
- public class LinkedListFeatures {
- public static void main(String[] args) {
- LinkedList<Pet> pets = new LinkedList<Pet>(Pets.arrayList(5));
- print(pets);
- // Identical:
- print("pets.getFirst(): " + pets.getFirst());
- print("pets.element(): " + pets.element());
- // Only differs in empty-list behavior:
- print("pets.peek(): " + pets.peek());
- // Identical; remove and return the first element:
- print("pets.remove(): " + pets.remove());
- print("pets.removeFirst(): " + pets.removeFirst());
- // Only differs in empty-list behavior:
- print("pets.poll(): " + pets.poll());
- print(pets);
- pets.addFirst(new Rat());
- print("After addFirst(): " + pets);
- pets.offer(Pets.randomPet());
- print("After offer(): " + pets);
- pets.add(Pets.randomPet());
- print("After add(): " + pets);
- pets.addLast(new Hamster());
- print("After addLast(): " + pets);
- print("pets.removeLast(): " + pets.removeLast());
- }
- }
- /* Output:
- [Rat, Manx, Cymric, Mutt, Pug]
- pets.getFirst(): Rat
- pets.element(): Rat
- pets.peek(): Rat
- pets.remove(): Rat
- pets.removeFirst(): Manx
- pets.poll(): Cymric
- [Mutt, Pug]
- After addFirst(): [Rat, Mutt, Pug]
- After offer(): [Rat, Mutt, Pug, Cymric]
- After add(): [Rat, Mutt, Pug, Cymric, Pug]
- After addLast(): [Rat, Mutt, Pug, Cymric, Pug, Hamster]
- pets.removeLast(): Hamster
- *///:~
- package com.java.util;
- // Making a stack from a LinkedList.
- import java.util.LinkedList;
- public class Stack<T> {
- private LinkedList<T> storage = new LinkedList<T>();
- public void push(T v) {
- storage.addFirst(v);
- }
- public T peek() {
- return storage.getFirst();
- }
- public T pop() {
- return storage.removeFirst();
- }
- public boolean empty() {
- return storage.isEmpty();
- }
- public String toString() {
- return storage.toString();
- }
- }
- package com.cy.container;
- //: holding/StackTest.java
- import com.java.util.*;
- public class StackTest {
- public static void main(String[] args) {
- Stack<String> stack = new Stack<String>();
- for(String s : "My dog has fleas".split(" "))
- stack.push(s);
- while(!stack.empty())
- System.out.print(stack.pop() + " ");
- }
- }
- /* Output:
- fleas has dog My
- *///:~
- package com.cy.container;
- //: holding/StackCollision.java
- public class StackCollision {
- public static void main(String[] args) {
- com.java.util.Stack<String> stack = new com.java.util.Stack<String>();
- for(String s : "My dog has fleas".split(" "))
- stack.push(s);
- while(!stack.empty())
- System.out.print(stack.pop() + " ");
- System.out.println();
- java.util.Stack<String> stack2 = new java.util.Stack<String>();
- for(String s : "My dog has fleas".split(" "))
- stack2.push(s);
- while(!stack2.empty())
- System.out.print(stack2.pop() + " ");
- }
- }
- /* Output:
- fleas has dog My
- fleas has dog My
- *///:~
- package com.cy.container;
- import java.util.*;
- public class SetOfInteger {
- public static void main(String[] args) {
- Random rand = new Random(47);
- Set<Integer> intset = new HashSet<Integer>();
- for(int i = 0; i < 10000; i++)
- intset.add(rand.nextInt(30));
- System.out.println(intset);
- }
- }
- //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18, 21, 20, 23, 22, 25, 24, 27, 26, 29, 28]
- package com.cy.container;
- import java.util.*;
- public class SortedSetOfInteger {
- public static void main(String[] args) {
- Random rand = new Random(47);
- SortedSet<Integer> intset = new TreeSet<Integer>();
- for(int i = 0; i < 10000; i++)
- intset.add(rand.nextInt(30));
- System.out.println(intset);
- }
- } /* Output:
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
- *///:~
- package com.cy.container;
- import java.util.*;
- public class Statistics {
- public static void main(String[] args) {
- Random rand = new Random(47);
- Map<Integer,Integer> m = new HashMap<Integer,Integer>();
- for(int i = 0; i < 10000; i++) {
- // Produce a number between 0 and 10:
- int r = rand.nextInt(10);
- Integer freq = m.get(r);
- m.put(r, freq == null ? 1 : freq + 1);
- }
- System.out.println(m);
- }
- } /* Output:
- {0=994, 1=1033, 2=1010, 3=1014, 4=958, 5=1000, 6=1052, 7=980, 8=946, 9=1013}
- *///:~
- package com.cy.container;
- import java.util.*;
- public class QueueDemo {
- public static void printQ(Queue queue) {
- while(queue.peek() != null)
- System.out.print(queue.remove() + " ");
- System.out.println();
- }
- public static void main(String[] args) {
- Queue<Integer> queue = new LinkedList<Integer>();
- Random rand = new Random(47);
- for(int i = 0; i < 10; i++)
- queue.offer(rand.nextInt(i + 10));
- printQ(queue);
- Queue<Character> qc = new LinkedList<Character>();
- for(char c : "Brontosaurus".toCharArray())
- qc.offer(c);
- printQ(qc);
- }
- } /* Output:
- 8 1 1 1 5 14 3 1 0 1
- B r o n t o s a u r u s
- *///:~
- package com.cy.container;
- import java.util.*;
- public class PriorityQueueDemo {
- public static void main(String[] args) {
- PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>();
- Random rand = new Random(47);
- for(int i = 0; i < 10; i++)
- priorityQueue.offer(rand.nextInt(i + 10));
- QueueDemo.printQ(priorityQueue);
- List<Integer> ints = Arrays.asList(25, 22, 20, 18, 14, 9, 3, 1, 1, 2, 3, 9, 14, 18, 21, 23, 25);
- priorityQueue = new PriorityQueue<Integer>(ints);
- QueueDemo.printQ(priorityQueue);
- priorityQueue = new PriorityQueue<Integer>(ints.size(), Collections.reverseOrder());
- priorityQueue.addAll(ints);
- QueueDemo.printQ(priorityQueue);
- String fact = "EDUCATION SHOULD ESCHEW OBFUSCATION";
- List<String> strings = Arrays.asList(fact.split(""));
- PriorityQueue<String> stringPQ = new PriorityQueue<String>(strings);
- QueueDemo.printQ(stringPQ);
- stringPQ = new PriorityQueue<String>(strings.size(), Collections.reverseOrder());
- stringPQ.addAll(strings);
- QueueDemo.printQ(stringPQ);
- Set<Character> charSet = new HashSet<Character>();
- for(char c : fact.toCharArray())
- charSet.add(c); // Autoboxing
- PriorityQueue<Character> characterPQ = new PriorityQueue<Character>(charSet);
- QueueDemo.printQ(characterPQ);
- }
- } /* Output:
- 0 1 1 1 1 1 3 5 8 14
- 1 1 2 3 3 9 9 14 14 18 18 20 21 22 23 25 25
- 25 25 23 22 21 20 18 18 14 14 9 9 3 3 2 1 1
- A A B C C C D D E E E F H H I I L N N O O O O S S S T T U U U W
- W U U U T T S S S O O O O N N L I I H H F E E E D D C C C B A A
- A B C D E F H I L N O S T U W
- *///:~
- package com.cy.container;
- import java.util.*;
- public class IterableClass implements Iterable<String> {
- protected String[] words = ("And that is how we know the Earth to be banana-shaped.").split(" ");
- @Override
- public Iterator<String> iterator() {
- return new Iterator<String>() {
- private int index = 0;
- public String next() {
- return words[index++];
- }
- public boolean hasNext() {
- return index < words.length;
- }
- public void remove() { // Not implemented
- throw new UnsupportedOperationException();
- }
- };
- }
- public static void main(String[] args) {
- for(String s : new IterableClass())
- System.out.print(s + " ");
- }
- }
- /* Output:
- And that is how we know the Earth to be banana-shaped.
- *///:~
- package com.cy.container;
- import java.util.*;
- public class EnvironmentVariables {
- public static void main(String[] args) {
- for(Map.Entry entry: System.getenv().entrySet()) {
- System.out.println(entry.getKey() + ": " + entry.getValue());
- }
- }
- }
- /*
- USERPROFILE: C:\Users\CY
- ProgramData: C:\ProgramData
- PATHEXT: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
- JAVA_HOME: D:\jdk1.7.0
- ProgramFiles(x86): C:\Program Files (x86)
- TEMP: C:\Users\CY\AppData\Local\Temp
- */
- package com.cy.container;
- import java.util.*;
- @SuppressWarnings("serial")
- class ReversibleArrayList<T> extends ArrayList<T> {
- public ReversibleArrayList(Collection<T> c) {
- super(c);
- }
- public Iterable<T> reversed() {
- return new Iterable<T>() {
- public Iterator<T> iterator() {
- return new Iterator<T>() {
- int current = size() - 1;
- @Override
- public boolean hasNext() {
- return current > -1;
- }
- @Override
- public T next() {
- return get(current--);
- }
- @Override
- public void remove() { // Not implemented
- throw new UnsupportedOperationException();
- }
- };
- }
- };
- }
- }
- public class AdapterMethodIdiom {
- public static void main(String[] args) {
- ReversibleArrayList<String> ral = new ReversibleArrayList<String>(Arrays.asList("To be or not to be".split(" ")));
- // Grabs the ordinary iterator via iterator():
- for(String s : ral)
- System.out.print(s + " ");
- System.out.println();
- // Hand it the Iterable of your choice
- for(String s : ral.reversed())
- System.out.print(s + " ");
- }
- } /* Output:
- To be or not to be
- be to not or be To
- *///:~
- package com.cy.container;
- import java.util.*;
- public class MultiIterableClass extends IterableClass {
- public Iterable<String> reversed() {
- return new Iterable<String>() {
- public Iterator<String> iterator() {
- return new Iterator<String>() {
- int current = words.length - 1;
- public boolean hasNext() { return current > -1; }
- public String next() { return words[current--]; }
- public void remove() { // Not implemented
- throw new UnsupportedOperationException();
- }
- };
- }
- };
- }
- public Iterable<String> randomized() {
- return new Iterable<String>() {
- public Iterator<String> iterator() {
- List<String> shuffled = new ArrayList<String>(Arrays.asList(words));
- Collections.shuffle(shuffled, new Random(47));
- return shuffled.iterator();
- }
- };
- }
- public static void main(String[] args) {
- MultiIterableClass mic = new MultiIterableClass();
- for(String s : mic.reversed())
- System.out.print(s + " ");
- System.out.println();
- for(String s : mic.randomized())
- System.out.print(s + " ");
- System.out.println();
- for(String s : mic)
- System.out.print(s + " ");
- }
- }
- /* Output:
- banana-shaped. be to Earth the know we how is that And
- is banana-shaped. Earth that how the be And we know to
- And that is how we know the Earth to be banana-shaped.
- *///:~
- package com.cy.container;
- import java.util.*;
- public class ModifyingArraysAsList {
- public static void main(String[] args) {
- Random rand = new Random(47);
- Integer[] ia = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
- List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));
- System.out.println("Before shuffling: " + list1);
- Collections.shuffle(list1, rand);
- System.out.println("After shuffling: " + list1);
- System.out.println("array: " + Arrays.toString(ia));
- List<Integer> list2 = Arrays.asList(ia);
- System.out.println("Before shuffling: " + list2);
- Collections.shuffle(list2, rand);
- System.out.println("After shuffling: " + list2);
- System.out.println("array: " + Arrays.toString(ia));
- }
- }
- /* Output:
- Before shuffling: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- After shuffling: [4, 6, 3, 1, 8, 7, 2, 5, 10, 9]
- array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- Before shuffling: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- After shuffling: [9, 1, 6, 3, 7, 2, 5, 10, 4, 8]
- array: [9, 1, 6, 3, 7, 2, 5, 10, 4, 8]
- *///:~

ThinkJava-持有对象的更多相关文章
- iOS 中的 block 是如何持有对象的
Block 是 Objective-C 中笔者最喜欢的特性,它为 Objective-C 这门语言提供了强大的函数式编程能力,而最近苹果推出的很多新的 API 都已经开始原生的支持 block 语法, ...
- java 持有对象
1.泛型和类型安全的容器 ArrayList,可以自动扩充大小的数组,add插入对象,get访问对象,size查看对象数目. 1 /** 2 * 泛型和类型安全的容器 3 * 2016/5/6 4 * ...
- Java基础 -- 持有对象(容器)
一 容器的用途 如果对象的数量与生命周期都是固定的,自然我们也就不需要很复杂的数据结构. 我们可以通过创建引用来持有对象,如 Class clazz; 也可以通过数组来持有多个对象,如 Class[] ...
- 工作随笔—Java容器基础知识分享(持有对象)
1. 概述 通常,程序总是运行时才知道的根据某些条件去创建新对象.在此之前,不会知道所需对象的数量,甚至不知道确切的类型,为解决这个普遍的编程问题:需要在任意时刻和任意位置创建任意数量的对象,所以,就 ...
- 走进Java中的持有对象(容器类)之一 容器分类
Java容器可以说是增强程序员编程能力的基本工具,本系列将带您深入理解容器类. 容器的用途 如果对象的数量与生命周期都是固定的,自然我们也就不需要很复杂的数据结构. 我们可以通过创建引用来持有对象,如 ...
- java 持有对象总结
java提供了大量的持有对象的方式: 1)数组将数字和对象联系起来,它保存类型明确的对象,查询对象时,不需要对结果做类型转换,它可以时多维的,可以保存基本数据类型的数据,但是,数组一旦生成,其容量就不 ...
- 《Think in Java》(十一)持有对象
Java 中的持有对象就是容器啦,看完这一章粗略的了解了 Java 中的容器框架以及常用实现!但是容器框架中的接口以及实现类有好多,下午还得好好看看第 17 章--容器深入研究以及 Java 官方的文 ...
- Thinking In Java持有对象阅读记录
这里记录下一些之前不太了解的知识点,还有一些小细节吧 序 首先,为什么要有Containers来持有对象,直接用array不好吗?——数组是固定大小的,使用不方便,而且是只能持有一个类型的对象,但当你 ...
- Java编程思想之十一 持有对象
如果一个程序只包含固定数量的且其生命期都是已知的对象,那么这是一个非常简单的程序. 11.1 泛型和类型安全的容器 使用ArrayList:创建一个实例,用add()插入对象,然后用get()访问对象 ...
- 持有对象:总结JAVA中的常用容器和迭代器,随机数 速查
JAVA使用术语“Collection”来指代那些表示集合的对象,JAVA提供的接口很多,首先我们先来记住他们的层次结构: java集合框架的基本接口/类层次结构 java.util.Collecti ...
随机推荐
- 如何高效使用Google
摘自http://simplyy.space/ 核心思想 1.首先,想好你想要寻找什么. 哪些词能够最好地描述你要寻找的信息或者概念? 哪些词是你能够用来替换的? 有没有那些词是可以不必包括在你想要搜 ...
- 关于如何使用cg中的discard/clip
Pass { ZTest Always Cull Off ZWrite Off Fog { Mode off } Blend Off CGPROGRAM #pragma vertex vert_img ...
- DevExpress v18.1新版亮点——ASP.NET篇(一)
用户界面套包DevExpress v18.1日前终于正式发布,本站将以连载的形式为大家介绍各版本新增内容.本文将介绍了DevExpress ASP.NET v18.1 的新功能,快来下载试用新版本!点 ...
- 去掉“Windows文件保护”
1.在“开始→运行”对话框中键入“gpedit.msc”,打开“本地计算机策略→计算机配置→管理模板→系统”窗口,找到“Windows文件保护”组,在右侧窗格中双击“设置Windows文件保护扫描”项 ...
- ios平台cocos2d-x播放音频、视频、音效的Demo(支持网络视频)
最近由ios应用转做游戏,游戏开始时需要播放一个视频,由于本身cocos2d-x播放视频的相关库,在网上搜到的资料都不是很全,我自己试过在cocos2dx直接调用ios的MediaPlayer来播放, ...
- jQuery之阻止默认事件以及解除阻止
大家都知道e.preventDefault()可以阻止默认时间,例如提交功能,但是怎么解除呢?以下参考于网络: 可以使用removeEventListener来移除.但是条件是addEventList ...
- 理解 LSTM 网络
递归神经网络 人类并不是每时每刻都从头开始思考.正如你阅读这篇文章的时候,你是在理解前面词语的基础上来理解每个词.你不会丢弃所有已知的信息而从头开始思考.你的思想具有持续性. 传统的神经网络不能做到这 ...
- 从 Python 第三方进度条库 tqdm 谈起 (转载)
原文地址: https://blog.ernest.me/post/python-progress-bar tqdm 最近一款新的进度条 tqdm 库比较热门,声称比老版的 python-progre ...
- LuoguP4389 付公主的背包【生成函数+多项式exp】
题目背景 付公主有一个可爱的背包qwq 题目描述 这个背包最多可以装10^5105大小的东西 付公主有n种商品,她要准备出摊了 每种商品体积为Vi,都有10^5105件 给定m,对于s\in [1,m ...
- CTF之当铺密码
当铺密码即:汉字的笔画有几笔出头,则代表数字几 例如:由=1 王=6 大=5