`

第11章持有对象

 
阅读更多

1.向上转型也可作用于泛型(当指定了某个确切类型作为类型参数时,不仅可以使用该确切类型,还可以使用该类型的子类类型)

2.容器分为Collection和Map两大类

(1)Collection,是一个元素序列,这些元素都服从一条或多条规则。list必须按照插入的顺序保存元素,Set不能有重复元素
(2)Map,表示一组成对的“键值对”对象。

3.所有的Collection都可以用foreach语法遍历;

4.迭代器,它是一个对象,它的工作是遍历并选择序列中的对象。而且它是个轻量级的对象,创建它的代价比较小。

5.java的Iterator只能单向移动,它的功能:

  (1).使用方法Iterator()要求容器返回一个Iterator对象。
  (2).next()方法获取序列中的下一个元素。


java.util.Iterator接口的相关方法
public interface Iterator<E>
1)
next

E next()

    Returns the next element in the iteration. Calling this method repeatedly until the hasNext() method returns false will return each

element in the underlying collection exactly once.

    Returns:
        the next element in the iteration.

2)
hasNext

boolean hasNext()

    Returns true if the iteration has more elements. (In other words, returns true if next would return an element rather than throwing

an exception.)

    Returns:
        true if the iterator has more elements.
3)
remove

void remove()

    Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called

only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is

in progress in any way other than by calling this method.
注意:这个删除方法最终会删除产生此迭代对象的容器中的对象。


6.
public class CrossContainerIteration {
public static void display(Iterator<Pet> it) {
while (it.hasNext()) {
Pet p = it.next();
System.out.print(p.id() + ":" + p + " ");
}
System.out.println();
}

public static void main(String[] args) {
ArrayList<Pet> pets = Pets.arrayList(8);
LinkedList<Pet> petsLL = new LinkedList<Pet>(pets);
HashSet<Pet> petsHS = new HashSet<Pet>(pets);
TreeSet<Pet> petsTS = new TreeSet<Pet>(pets);
display(pets.iterator());
display(petsLL.iterator());
display(petsHS.iterator());
display(petsTS.iterator());
}
}

从上面的例子可以看到,display方法不包含任何有关它所遍历的序列的类型信息,这展示了Iterator的真正威力:能够建遍历序列的操作与序列底层的结构分离。迭代器统一了对容器的访问方式。

7.ListIterator是一个更加强大的Iterator的子类型,它只能用于各种List类的访问。普通的Iterator只能向前移动,但是ListIterator可以双向移动。
import java.util.List;
import java.util.ListIterator;

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()+",");
}
    System.out.println();
it = pets.listIterator(3);
while(it.hasNext()){
System.out.print(it.next()+",");
}
System.out.println();
while(it.hasPrevious()){
System.out.print(it.previous()+",");
}
System.out.println();
while (it.hasNext()) {
it.next();
    it.set(new Pug());
}
System.out.println(pets);
}
}
//outputs下面有相关方法的使用介绍
Rat,Manx,Cymric,Mutt,Pug,Cymric,Pug,Manx,
Mutt,Pug,Cymric,Pug,Manx,
Manx,Pug,Cymric,Pug,Mutt,Cymric,Manx,Rat,
[Pug, Pug, Pug, Pug, Pug, Pug, Pug, Pug]
对迭代器的操作,最终会影响到产生此迭代器的容器

接口
public interface ListIterator<E>
extends Iterator<E>

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain

the iterator's current position in the list. A ListIterator has no current element; its cursor position always lies between the element

that would be returned by a call to previous() and the element that would be returned by a call to next(). In a list of length n, there

are n+1 valid index values, from 0 to n, inclusive.

          Element(0)   Element(1)   Element(2)   ... Element(n)  
        ^            ^            ^            ^               ^
Index: 0            1            2            3               n+1
相关方法:
1)hasNext

boolean hasNext()

    Returns true if this list iterator has more elements when traversing the list in the forward direction. (In other words, returns

true if next would return an element rather than throwing an exception.)
2)next

E next()

    Returns the next element in the list. This method may be called repeatedly to iterate through the list, or intermixed with calls to

previous to go back and forth. (Note that alternating calls to next and previous will return the same element repeatedly.)

3)
hasPrevious

boolean hasPrevious()

    Returns true if this list iterator has more elements when traversing the list in the reverse direction. (In other words, returns

true if previous would return an element rather than throwing an exception.)
4)previous

E previous()

    Returns the previous element in the list. This method may be called repeatedly to iterate through the list backwards, or intermixed

with calls to next to go back and forth. (Note that alternating calls to next and previous will return the same element repeatedly.)

    Returns:
        the previous element in the list.
5)nextIndex

int nextIndex()

    Returns the index of the element that would be returned by a subsequent call to next. (Returns list size if the list iterator is at

the end of the list.)

    Returns:
        the index of the element that would be returned by a subsequent call to next, or list size if list iterator is at end of list.

6)previousIndex

int previousIndex()

    Returns the index of the element that would be returned by a subsequent call to previous. (Returns -1 if the list iterator is at the

beginning of the list.)

7)set

void set(E o)

    Replaces the last element returned by next or previous with the specified element (optional operation). This call can be made only

if neither ListIterator.remove nor ListIterator.add have been called after the last call to next or previous.

    Parameters:
        o - the element with which to replace the last element returned by next or previous.


8.java.util.List接口的方法
listIterator

ListIterator<E> listIterator(int index)

    Returns a list iterator of the elements in this list (in proper sequence), starting at the specified position in this list. The

specified index indicates the first element that would be returned by an initial call to the next method. An initial call to the

previous method would return the element with the specified index minus one.

Parameters:
    index - index of first element to be returned from the list iterator (by a call to the next method).

Returns:
    a list iterator of the elements in this list (in proper sequence), starting at the specified position in this list.

9.List接口在Collection接口的基础上添加了大量的方法,有两种基本类型的List

1)ArrayList,擅长于随机访问元素,但是插入、删除较慢;
2)LinkedList,擅长于插入、删除元素,随机访问比较慢;

10.LinkedList还添加了可以使其用作栈、队列或双端队列的方法,例如:

该类相关方法说明:
1)getFirst

public E getFirst()

    Returns the first element in this list.

    Returns:
        the first element in this list
2)element

public E element()

    Retrieves, but does not remove, the head (first element) of this list.

    Returns:
        the head of this queue.
3)peek

public E peek()

    Retrieves, but does not remove, the head (first element) of this list.

    Returns:
        the head of this queue, or null if this queue is empty.
4)remove

public E remove(int index)

    Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their

indices). Returns the element that was removed from the list.
Parameters:
    index - the index of the element to removed.
Returns:
    the element previously at the specified position.
5)removeFirst

public E removeFirst()

    Removes and returns the first element from this list.

    Returns:
        the first element from this list.
6)poll

public E poll()

    Retrieves and removes the head (first element) of this list.
Returns:
    the head of this queue, or null if this queue is empty.
7)offer

public boolean offer(E o)

    Adds the specified element as the tail (last element) of this list.

    Parameters:
        o - the element to add.
    Returns:
        true (as per the general contract of Queue.offer)
8)addLast

public void addLast(E o)

    Appends the given element to the end of this list. (Identical in function to the add method; included only for consistency.)

    Parameters:
        o - the element to be inserted at the end of this list.

9)removeLast

public E removeLast()

    Removes and returns the last element from this list.

    Returns:
        the last element from this list.

11.用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(); }
}
这里最后不要使用继承,这样会产生具有LinkedList行为的类,还是用组合比较好。
尽管已经有java.util.Stack,但是LinkedList可以产生更好的Stack,首先使用LinkedList实现的Stack。

12.Set不保存重复的元素。因此,可以很容易地询问某个元素是否在Set中。正因为这样,查找就成了Set中最重要的操作。而HashSet对快速查找进行了优化。Set根Collection具有完全一样的接口,因此没有任何额外的功能

13.如果想对结果进行排序,可以使用TreeSet而不是HashSet,例如:
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);
  }

java.util.Set接口的相关方法:
1)contains

boolean contains(Object o)

    Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e

such that (o==null ? e==null : o.equals(e)).
Parameters:
    o - element whose presence in this set is to be tested.
Returns:
    true if this set contains the specified element.
2)containsAll

boolean containsAll(Collection<?> c)

    Returns true if this set contains all of the elements of the specified collection. If the specified collection is also a set, this

method returns true if it is a subset of this set.

3)removeAll

boolean removeAll(Collection<?> c)

    Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified

collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two

sets.
4)addAll

boolean addAll(Collection<? extends E> c)

    Adds all of the elements in the specified collection to this set if they're not already present (optional operation). If the

specified collection is also a set, the addAll operation effectively modifies this set so that its value is the union of the two sets.

The behavior of this operation is unspecified if the specified collection is modified while the operation is in progress.

    Parameters:
        c - collection whose elements are to be added to this set.
    Returns:
        true if this set changed as a result of the call.

14.
Map可以将对象映射到其他对象上。下面的例子很容易地用Map将随机数产生的次数纪录了下来
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 20:
int r = rand.nextInt(20);
Integer freq = m.get(r);
m.put(r, freq == null ? 1 : freq + 1);
}
System.out.println(m);
}
}
map接口的相关方法:
1)get

V get(Object key)

    Returns the value to which this map maps the specified key. Returns null if the map contains no mapping for this key. A return value

of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the

key to null. The containsKey operation may be used to distinguish these two cases.

    More formally, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this

method returns v; otherwise it returns null. (There can be at most one such mapping.)

    Parameters:
        key - key whose associated value is to be returned.
    Returns:
        the value to which this map maps the specified key, or null if the map contains no mapping for this key.
2)put

V put(K key,
      V value)

    Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping

for this key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if

m.containsKey(k) would return true.))

    Parameters:
        key - key with which the specified value is to be associated.
        value - value to be associated with the specified key.
    Returns:
        previous value associated with specified key, or null if there was no mapping for key. A null return can also indicate that the

map previously associated null with the specified key, if the implementation supports null values.


15.Map接口相关方法:
public class PetMap {
public static void main(String[] args) {
Map<String, Pet> petMap = new HashMap<String, Pet>();
petMap.put("My Cat", new Cat("Molly"));
petMap.put("My Dog", new Dog("Ginger"));
petMap.put("My Hamster", new Hamster("Bosco"));
System.out.println(petMap);
Pet dog = petMap.get("My Dog");
System.out.println(dog);
System.out.println(petMap.containsKey("My Dog"));
System.out.println(petMap.containsValue(dog));
}
}
1)containsKey

boolean containsKey(Object key)

    Returns true if this map contains a mapping for the specified key. More formally, returns true if and only if this map contains a

mapping for a key k such that (key==null ? k==null : key.equals(k)). (There can be at most one such mapping.)

    Parameters:
        key - key whose presence in this map is to be tested.
    Returns:
        true if this map contains a mapping for the specified key.

2)containsValue

boolean containsValue(Object value)

    Returns true if this map maps one or more keys to the specified value. More formally, returns true if and only if this map contains

at least one mapping to a value v such that (value==null ? v==null : value.equals(v)). This operation will probably require time linear

in the map size for most implementations of the Map interface.

    Parameters:
        value - value whose presence in this map is to be tested.
    Returns:
        true if this map maps one or more keys to the specified value.

16.Map的值可以是其他容器,甚至是其他Map值

public class MapOfList {
public static Map<Person, List<? extends Pet>> petPeople = new HashMap<Person, List<? extends Pet>>();
static {
petPeople.put(new Person("Dawn"), Arrays.asList(new Cymric("Molly"),
new Mutt("Spot")));
petPeople.put(new Person("Kate"), Arrays.asList(new Cat("Shackleton"),
new Cat("Elsie May"), new Dog("Margrett")));
petPeople.put(new Person("Marilyn"), Arrays.asList(new Pug(
"Louie aka Louis Snorkelstein Dupree"), new Cat(
"Stanford aka Stinky el Negro"), new Cat("Pinkola")));
petPeople.put(new Person("Luke"), Arrays.asList(new Rat("Fuzzy"),
new Rat("Fizzy")));
petPeople.put(new Person("Isaac"), Arrays.asList(new Rat("Freckly")));
}

public static void main(String[] args) {
System.out.println("People: " + petPeople.keySet());
System.out.println("Pets: " + petPeople.values());
for (Person person : petPeople.keySet()) {
System.out.println(person + " has:");
for (Pet pet : petPeople.get(person))
System.out.println("    " + pet);
}
}
}
相关方法:
1)keySet

Set<K> keySet()

    Returns a set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set,

and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove

operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from

the map, via the Iterator.remove, Set.remove, removeAll retainAll, and clear operations. It does not support the add or addAll

operations.

    Returns:
        a set view of the keys contained in this map.
2)values

Collection<V> values()

    Returns a collection view of the values contained in this map. The collection is backed by the map, so changes to the map are

reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except

through the iterator's own remove operation), the results of the iteration are undefined. The collection supports element removal, which

removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations.

It does not support the add or addAll operations.

    Returns:
        a collection view of the values contained in this map.


17.
public class MapOfList {
public static Map<String, String> petPeople = new HashMap<String, String>();
static {
petPeople.put("1","Dawn");
petPeople.put("2","Kate");
petPeople.put("3","Marilyn");

}

public static void main(String[] args) {
System.out.println("People: " + petPeople.keySet());
System.out.println("Pets: " + petPeople.values());
Set<Map.Entry<String, String>> s=petPeople.entrySet();
System.out.println(s);


}
}
Map可以返回它的键的Set,它的值的Collection,或者它的键值对的Set

Map.entrySet()返回的是 Map.Entry<K,V>的集合。Map.Entry本身不是Collection。java.util.Map.Entry接口主要就是在遍历map的时候用到。

18.队列是一个先进先出的容器。LinkedList实现了Queue接口因此它可以用作Queue的一种实现,例如:
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);
}
}

19.优先级队列声明下一个弹出元素是最需要的元素(具有最高的优先级)。

分享到:
评论

相关推荐

    第十一章 持有对象

    这一章的主题"第十一章 持有对象"可能探讨的是如何在程序中有效地管理和控制对象的生命周期,特别是在Java、C++或者.NET等面向对象编程语言中的应用场景。持有对象涉及到的关键知识点包括引用计数、智能指针、垃圾...

    think in java 第11章 持有对象

    第11章的主题是“持有对象”,这一章主要探讨了如何在Java中创建和管理对象,包括对象的引用、对象的生命周期、类与对象的关系,以及如何通过集合来存储和操作对象。以下是对这些知识点的详细解释: 1. **对象引用*...

    Java编程思想第11章持有对象.ppt

    【Java编程思想第11章持有对象】 在Java编程中,持有对象是一个核心概念,它涉及到如何有效地管理和操作对象集合。本章主要讨论了两个关键主题:泛型和容器类,特别是Collection家族和Map家族的其他成员,以及迭代...

    Java编程思想笔记(全)

    第十一章关注于如何持有对象以及对象之间的引用关系。本章探讨了对象引用的各种方式,包括强引用、软引用、弱引用和虚引用,并讨论了它们各自的用途。此外,还会介绍垃圾回收机制如何处理这些不同类型的引用,以及...

    编程思想下篇

    第11章 持有对象 第12章 通过异常处理错误 第13章 字符串 第14章 类型信息 第15章 泛型 第16章 数组 第17章 容器深入研究 第18章 Java I/O系统 第19章 枚举类型 第20章 注解 第21章 并发 第22章 图形化用户界面

    Thinking in java4(中文高清版)-java的'圣经'

    非静态实例初始化 5.8 数组初始化 5.8.1 可变参数列表 5.9 枚举类型 5.10 总结 第6章 访问权限控制 第7章 复用类 第8章 多态 第9章 接口 第10章 内部类 第11章 持有对象 第12章 通过异常处理错误 第13章 字符串 第...

    thinkinjava源码-Thinking-in-Java:ThinkingInJava源代码和练习题

    第11章 持有对象 第12章 通过异常处理错误 第13章 字符串 第14章 类型信息 第15章 泛型 第16章 数组 第17章 容器深入研究 第18章 Java I/O系统 第19章 枚举类型 第20章 注解 第21章 并发 第22章 图形化用户界面 水平...

    swift学习第三章

    第十一节“函数式编程”部分,我们接触了Swift中的高阶函数(Higher-Order Functions)和闭包(Closures)。高阶函数可以接受一个或多个函数作为参数,或者返回一个函数作为结果,这在处理数据集合时非常有用。闭包...

    《财政学》第11章税收制度.ppt

    综上所述,《财政学》第11章税收制度部分为我们提供了一个全面了解和分析税收体系、税收分类及其在宏观经济政策中作用的视角。通过对税收制度的深入研究,可以更好地理解政府的财政政策如何影响国家的经济运行和社会...

    第11章-数据库的安全性和控制

    【第11章-数据库的安全性和控制】 数据库的安全性是确保数据不被未经授权的个人访问或修改的关键方面,尤其对于初学者来说,理解并掌握这一主题至关重要。安全性和完整性是两个不同的概念,前者关注防止非法用户的...

    C#应用程序设计教程 第11章 数据库与ADO.ppt

    在C#应用程序设计中,第11章着重讲解了如何使用数据库和ADO.NET技术来创建数据库应用系统。数据库是组织和存储数据的核心,常见的数据库管理系统包括FoxPro、Sybase、Access、Oracle以及SQL Server,它们大多基于...

    财政学第11章税收制度PPT学习教案.pptx

    第11章主要探讨了税收体系的构成和分类,以及税制结构的设计。税收体系包括个人所得税、公司所得税、社会保险税、财产税、遗产和赠与税、营业税、增值税、关税等多种税种,这些税种依据征税对象在经济活动中的不同...

    Think in java学习笔记

    #### 第11章:持有对象 - **对象的持有方式**:包括强引用、软引用、弱引用和虚引用等不同类型的引用。 #### 第12章:通过异常处理错误 - **异常处理**:介绍了异常的分类、捕获和抛出机制。 #### 第13章:字符...

    Java基础入门自学课件 第11章 泛型(共4页).rar

    在这个“Java基础入门自学课件 第11章 泛型”中,我们可以期待学习到以下几个核心知识点: 1. **泛型的基本概念**:泛型允许我们在定义类、接口和方法时指定一种或多种类型参数,这样在实际使用时可以传入具体的...

    操作系统原理:第十四章 保护.ppt

    这一章主要讲解了保护系统的目标、保护域、访问矩阵的实现、访问权限的撤回、基于权限的系统以及基于语言的保护等概念。 首先,保护目标是确保操作系统中的各个对象(如硬件资源、软件模块、数据文件等)只能被授权...

    Android第十八章Android架构模式

    "Android第十八章Android架构模式"可能涵盖了一系列用于优化Android应用程序设计的模式。这些模式旨在提高代码的可读性、测试性和可复用性,从而降低长期维护成本。在本章节中,我们可能会学习到以下几种常见的...

    数据库第四版答案(王珊萨师煊)第11章并发控制[参照].pdf

    共享锁(S锁)则允许事务读取数据,但不允许修改,并且允许多个事务同时持有相同数据对象的共享锁。通过合理的封锁协议,比如两阶段封锁协议,可以有效地避免数据不一致问题。 两阶段封锁协议是一种经典的封锁协议...

    第17章移动语义.pdf

    移动语义是C++11引入的一种优化机制,主要目的是提高程序性能,特别是涉及资源重分配的情况。在C++中,对象分为两种类型:左值(lvalue)和右值(rvalue)。左值可以是变量,可以有名字并且可以被再次引用,而右值...

    第11章 枚举_注解_内部类.docx

    在Java编程语言中,枚举(Enumeration)是一种特殊的数据类型,自Java 5开始引入,主要用来表示一组有限且固定的值。枚举类型是类的一个子类型,继承自`java.lang.Enum`基类,不能手动定义子类。使用枚举可以提高...

    心理学-第十四章-态度与品德心理.ppt

    《心理学-第十四章-态度与品德心理》这一章节深入探讨了态度与品德的形成、结构、特征以及它们在个体行为中的作用和影响。 态度这一概念,在心理学中指的是个体对特定事物或观念所持有的相对稳定的评价、情感和行为...

Global site tag (gtag.js) - Google Analytics