Holding Your Objects


  • In general, your programs will always be creating new objects based on some criteria that will be known only at run time.
  • You can’t rely on creating a named reference to hold each one of your objects.
  • The compiler-supported type is the array. if you want to hold a group of primitives.
  • The fixed-sized constraint of an array is too limiting.
  • Containers(collection classes) provide sophisticated ways to hold your objects, and you can solve a surprising number of problems by using these tools.
  • Java container classes will automatically resize themselves.
  • You don’t need to worry about how big to make the container while you’re writing the program.

Generics and type-safe containers

  • With generics, you’re prevented, at compile time, from putting the wrong type of object into a container.
  • With generics you not only know that the compiler will check the type of object that you put into a container, but you also get cleaner syntax when using the objects in the container.
  • Upcasting works the same with generics as it does with other types.

Basic concepts

  • The only place where you’ll specify the precise type you’re using is at the point of creation.
  • The intent of using the interface is that if you decide you want to change your implementation, all you need to do is change it at the point of creation.
  • This approach won’t always work, because some classes have additional functionality.

Adding groups of elements

  • Collections.addAll( ) runs much faster, and it’s just as easy to construct the Collection with no elements and then call Collections.addAll( ), so this is the preferred approach.
  • A limitation of Arrays.asList( ) is that it takes a best guess about the resulting type of the List, and doesn’t pay attention to what you’re assigning it to.
  • explicit type argument specification——it’s possible to insert a "hint" in the middle of Arrays.asList( ), to tell the compiler what the actual target type should be for the resulting List type produced by Arrays.asList( ).

Printing containers

  • Two primary categories in the Java container library. The distinction is based on the number of items that are held in each "slot" in the container.
  • The Collection category only holds one item in each slot. A Map holds two objects, a key and an associated value, in each slot.
  • A LinkedList contains more operations than an ArrayList.
  • A Set will only hold one of each identical item, the different Set implementations store the elements differently.
  • A Map only accepts one of each key.
  • You don’t have to specify (or think about) the size of the Map because it resizes itself automatically.
  • The HashMap implementation uses a very fast algorithm that controls the order.

List

  • The List interface adds a number of methods to Collection that allow insertion and removal of elements in the middle of a List.
  • That’s its fundamental value: a modifiable sequence.
  • If you want to remove an object, you can pass that object’s reference to the remove( ) method.
  • It’s important to be aware that List behavior changes depending on equals( ) behavior.
  • For a LinkedList, insertion and removal in the middle of a list is a cheap operation (except for, in this case, the actual random access into the middle of the list), but for an ArrayList it is an expensive operation.
  • Optimization is a tricky issue, and the best policy is to leave it alone until you discover you need to worry about it.
  • It’s also interesting to note that order is unimportant for** subList( )** method.
  • subList( ) produces a list backed by the original list. Therefore, changes in the returned list are reflected in the original list, and vice versa.
  • You don’t have to worry about equals( ) behavior when using indexes.

Iterator

  • In a List, add( ) is one way to insert elements, and get( ) is one way to fetch elements.
  • You need to program to the exact type of the container in order to use it.
  • You’d like to write, from the beginning, a piece of general-purpose code that doesn’t know or care what type of container it’s working with, so that it can be used on different types of containers without rewriting that code.
  • An iterator is an object whose job is to move through a sequence and select each object in that sequence without the client programmer knowing or caring about the underlying structure of that sequence.
  • With an Iterator, you don’t need to worry about the number of elements in the container.
  • An Iterator will also remove the last element produced by next( ), which means you must call next( ) before you call remove( ).
  • The true power of the Iterator: the ability to separate the operation of traversing a sequence from the underlying structure of that sequence.

ListIterator

  • The ListIterator is a more powerful subtype of Iterator that is produced only by List classes.
  • ListIterator is bidirectional.

LinkedList

  • The LinkedList performs certain operations (insertion and removal in the middle of the List) more efficiently than does ArrayList. Conversely, it is less efficient for random-access operations.
  • LinkedList also adds methods that allow it to be used as a stack, a Queue or a double-ended queue (deque).
  • The element( ), offer( ), peek( ), poll( ) and remove( ) methods that were added to LinkedList in order that it could be a Queue implementation.

Stack

  • LinkedList has methods that directly implement stack functionality.
  • There is no common Stack interface in java.util.
  • Even though java.util.Stack exists, LinkedList produces a better Stack.

Set

  • A Set refuses to hold more than one instance of each object value.
  • The most common use for a Set is to test for membership.
  • A HashSet implementation is optimized for rapid lookup.
  • Set has the same interface as Collection, so there isn’t any extra functionality like there is in the two different types of List.
  • A Set determines membership based on the "value" of an object.
  • TreeSet keeps elements sorted into a red-black tree data structure, whereas HashSet uses the hashing function. LinkedHashSet also uses hashing for lookup speed, but appears to maintain elements in insertion order using a linked list.

Map

  • You can’t use primitives with containers.
  • Maps, like arrays and Collections, can easily be expanded to multiple dimensions.
  • Thus, it’s quite easy to combine containers to quickly produce powerful data structures.

Queue

  • Queues are commonly used as a way to reliably transfer objects from one area of a program to another.
  • Queues are especially important in concurrent programming, because they safely transfer objects from one task to another.
  • LinkedList has methods to support queue behavior and it implements the Queue interface, so a LinkedList can be used as a Queue implementation.
  • The Queue interface narrows access to the methods of LinkedList so that only the appropriate methods are available, and you are thus less tempted to use LinkedList methods.
  • You can have a usable Queue without any of the methods that are in Collection, from which it is inherited.

PriorityQueue

  • First-in, first-out says that the next element should be the one that was waiting the longest.
  • A priority queue says that the element that goes next is the one with the greatest need (the highest priority).
  • If you build a messaging system, some messages will be more important than others, and should be dealt with sooner, regardless of when they arrive.
  • When you offer( ) an object onto a PriorityQueue, that object is sorted into the queue.
  • The PriorityQueue ensures that when you call peek( ), poll( ) or remove( ), the element you get will be the one with the highest priority.
  • If you want you use your own class in a PriorityQueue, you must include additional functionality to produce natural ordering, or provide your own Comparator.

Collection vs. Iterator

  • In Java, it might seem sensible to follow the C++ approach, and to express commonality between containers using an iterator rather than a Collection.
  • Implementing Collection also means providing an iterator( ) method.
  • The use of Iterator becomes compelling when you implement a foreign class, one that is not a Collection, in which it would be difficult or annoying to make it implement the Collection interface.
  • Producing an Iterator is the least-coupled way of connecting a sequence to a method that consumes that sequence, and puts far fewer constraints on the sequence class than does implementing Collection.

Foreach and iterators

  • Working with foreach is a characteristic of all Collection objects.
  • The Iterable interface is what foreach uses to move through a sequence.
  • A foreach statement works with an array or anything Iterable, but that doesn’t mean that an array is automatically an Iterable, nor is there any autoboxing that takes place.

The Adapter Method idiom

  • What if you have an existing class that is Iterable, and you’d like to add one or more new ways to use this class in a foreach statement?
  • One solution is what I call the Adapter Method idiom.
  • When you have one interface and you need another one, writing an adapter solves the problem.
  • It’s important to be aware that Arrays.asList( ) produces a List object that uses the underlying array as its physical implementation.
  • If you do anything to that List that modifies it, and you don’t want the original array modified, you should make a copy into another container.

Thinking in Java——笔记(11)的更多相关文章

  1. Java笔记11:JSP连接Oracle数据库

    1 建立Web项目 在D:\tomcat\webapps\中建立basicSyntax项目,在该项目中添加WEB-INF,WEB-INF\classes\,WEB-INF\lib\和WEB-INF\w ...

  2. java笔记11之二维数组

    格式1: 二维数组:就是元素为一维数组的一个数组 数据类型[][] 数组名 = new 数组类型[m][n] 其中m为行 n为列 注意: A:以下格式也可以表示二维数组            a:数据 ...

  3. JAVA自学笔记11

    JAVA自学笔记11 1:Eclipse的安装 2:用Eclipse写一个HelloWorld案例,最终在控制台输出你的名字 A:创建项目 B:在src目录下创建包.cn.itcast C:在cn.i ...

  4. java 笔记(4) —— java I/O 流、字节流、字符流

    Java中使用流来处理程序的输入和输出操作,流是一个抽象的概念,封装了程序数据于输入输出设备交换的底层细节.JavaIO中又将流分为字节流和字符流,字节流主要用于处理诸如图像,音频视频等二进制格式数据 ...

  5. Spring MVC 学习笔记11 —— 后端返回json格式数据

    Spring MVC 学习笔记11 -- 后端返回json格式数据 我们常常听说json数据,首先,什么是json数据,总结起来,有以下几点: 1. JSON的全称是"JavaScript ...

  6. java笔记整理

    Java 笔记整理 包含内容     Unix Java 基础, 数据库(Oracle jdbc Hibernate pl/sql), web, JSP, Struts, Ajax Spring, E ...

  7. 并发编程学习笔记(11)----FutureTask的使用及实现

    1. Future的使用 Future模式解决的问题是.在实际的运用场景中,可能某一个任务执行起来非常耗时,如果我们线程一直等着该任务执行完成再去执行其他的代码,就会损耗很大的性能,而Future接口 ...

  8. MOOC JAVA笔记

    MOOC JAVA笔记 1.基础了解 JDK是开发人员安装的,它提供了开发java程序的必须工具 JRE是普通用户安装的,它提供了java的运行环境 JVM是java虚拟机运行程序的核心 2.程序的移 ...

  9. Effective Java笔记一 创建和销毁对象

    Effective Java笔记一 创建和销毁对象 第1条 考虑用静态工厂方法代替构造器 第2条 遇到多个构造器参数时要考虑用构建器 第3条 用私有构造器或者枚举类型强化Singleton属性 第4条 ...

随机推荐

  1. Android 光线传感器的调用

    1.activity如果要使用传感器,就必须实现SensorEventListener接口 2.得到传感器管理对象(sensormanager) 3.使用sensormanager.registerl ...

  2. POJ 3678 Katu Puzzle

    Description 给出一个关系,包括 And,Xor,Or 问是否存在解. Sol 经典的2-SAT问题. 把每个值看成两个点,一个点代表选 \(0\) ,另一个代表选 \(1\) . 首先来看 ...

  3. VC++ 一个简单的Log类

    在软件开发中,为程序建立Log日志是很必要的,它可以记录程序运行的状态以及出错信息,方便维护和调试. 下面实现了一个简单的Log类,使用非常简单,仅供参考. // CLogHelper.h : hea ...

  4. CoreAnimation 之CAReplicatorLayer

    CAReplicatorLayer: 主要作用有以下两个: CAReplicatorLayer的目的是为了高效生成许多相似的图层,它会绘制一个或多个图层的子图层 并在每个复制体上应用不同的变换 使用C ...

  5. 踩个猴尾不容易啊 Canvas画个猴子

    踩个猴尾不容易啊  Canvas画个猴子 <!DOCTYPE html> <html> <head> <meta charset="UTF-8&qu ...

  6. CozyRSS开发记录2-酷炫的皮肤库

    CozyRSS开发记录2-酷炫的皮肤库 1.MaterialDesignToolkit 最开始微软推出Metro设计风格的时候,有人喜欢有人喷.紧接着,Ios也开始做扁平化的UI,这时候,扁平化已成为 ...

  7. 在Salesforce中创建Approval Process

    在Salesforce中可以创建Approval Process来实现审批流程的功能,实际功能与我们常说的Workflow很相似,具体的设置步骤如下所示 1):选择对应的Object去创建对应的App ...

  8. 反调试技术常用API,用来对付检测od和自动退出程序

    在调试一些病毒程序的时候,可能会碰到一些反调试技术,也就是说,被调试的程序可以检测到自己是否被调试器附加了,如果探知自己正在被调试,肯定是有人试图反汇编啦之类的方法破解自己.为了了解如何破解反调试技术 ...

  9. YUV RGB播放器 打开, 显示RGB数据

    可以查看RGB像素数据 可以通过菜单栏打开像素数据文件,也可以通过拖拽方式打开文件.如果文件名称中包含了“{w}x{h}”这样的字符串(例如“test_320x420.yuv”),系统会自动解析为该像 ...

  10. jvm的垃圾回收原理

    什么是垃圾回收? 垃圾回收是Java中自动内存管理的另一种叫法.垃圾回收的目的是为程序保持尽可能多的可用堆(heap). JVM会删除堆上不再需要从堆引用的对象. 用一个例子解释垃圾回收? 比方说,下 ...