Thinking in Java——筆記(11)

来源:http://www.cnblogs.com/apolloqq/archive/2016/12/11/6160881.html
-Advertisement-
Play Games

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 ...


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.
    

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Session 是保存用戶和 Web 應用的會話狀態的一種方法,ASP.NET Core 提供了一個用於管理會話狀態的中間件。在本文中我將會簡單介紹一下 ASP.NET Core 中的 Session 的使用方法。 安裝配置 Session 在 project.json 添加引用 Microsoft ...
  • 1.DbContext怎麼在Asp.mvc中使用? 這麼定義之後,所有需要用到DbContext對象的地方,都調這個方法。 2. 不要隨便using或Dispose DbContext會導致延遲載入的不可用,還會有一些其他錯誤 如IQueryable<T> 下麵的方法(.First() /.Coun ...
  • 從此刻開始,我已封閉!概不接客! 像風一樣的男人,像風一樣的性格,無拘無束,不拘一格。那麼問題來了,當風遇到沙,不一定你是風兒,我是沙兒的纏纏綿綿,。也許是漫天黃沙,飛粒走石。如果我們期望擒住這漫天的塵埃,必須有強有力的手臂!那麼曬網、撒網、收網!讓他老實的封閉起來吧,永遠相依偎,阿拉! 讀在最前面 ...
  • 最終的解決方案是:https://github.com/liuyunzhuge/php_weixin_provider,詳細的介紹請往下閱讀。 本文面向的是php語言laravel框架的用戶,介紹的是基於該框架實現的一個簡易集成微信登錄的方法。使用方法如下: 1. 安裝php_weixin_prov ...
  • 今日問題: 請問主程式中輸出結果是什麼?(點擊以下“【Java每日一題】20161212”查看20161209問題解析) 題目原發佈於公眾號、簡書:【Java每日一題】20161212,【Java每日一題】20161212 ...
  • 關於springMVC中的session,有2種使用方法,第一種是直接傳遞httpsession,第二種是使用@SessionAttributes("userId") 註解 這裡附帶一個帖子,別人寫的特別好,是我看過的覺得最好的:http://www.cnblogs.com/waytofall/p/ ...
  • 需求 加入我們需要處理一串個位數(0~9),奇數時需要迴圈列印它;偶數則等待對應時長並完成所有任務;0則是錯誤,但不需要終止任務,可以自定義一些處理。 關鍵點 定義func函數處理需求 callback處理返回結果,只有偶數和0返回;奇數會一直執行;要控制線程池狀態,則需要針對偶數和0時拋出異常,並... ...
  • 嵌入式web伺服器不同於傳統伺服器,web需要轉換成數組格式保存在flash中,才方便lwip網路介面的調用,最近因為業務需求,需要頻繁修改網頁,每次的壓縮和轉換就是個很繁瑣的過程,因此我就有了利用所掌握的知識,利用python編寫個能夠批量處理網頁文件,壓縮並轉換成數組的腳本。 腳本運行背景(後續 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...