11.持有對象

集合類:list(特定順序) set(元素不重復) queue(一端插入,一端移除) map(鍵值對)


IMG_20160914_200025.jpg

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));
// Runs significantly faster, but you can't
// construct a Collection this way:
Collections.addAll(collection, 11, 12, 13, 14, 15);
Collections.addAll(collection, moreInts);
// 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.

Collection.addAll():只能接受另一個Collection對象作參數
Collections.addAll():參數列表可變,運行速度更快
Arrays.asList():參數列表可變,直接使用方法返回是一個固定大小的數組


list

Arraylist:隨機訪問快,插入和移除慢
Linkedlist:利于插入和移除,隨機訪問慢

注意List有些方法行為依賴于equals()方法


迭代器

迭代器(一種設計模式),它可以遍歷并選擇序列中的對象,而不用關心序列底層的結構。

不用知道容器的確切類型,統一了對容器的訪問方式

iterator()
next()
hasNext()
remove()

List<Pet> pets = Pets.arrayList(12);
Iterator<Pet> it = pets.iterator();
while(it.hasNext()) {
  Pet p = it.next();
  System.out.print(p.id() + ":" + p + " ");
}
System.out.println();
// A simpler approach, when possible:
for(Pet p : pets)
  System.out.print(p.id() + ":" + p + " ");
System.out.println();   
// An Iterator can also remove elements:
it = pets.iterator();
for(int i = 0; i < 6; i++) {
  it.next();
  it.remove();
}
System.out.println(pets);

/* Output:
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx 8:Cymric 9:Rat 10:EgyptianMau 11:Hamster
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx 8:Cymric 9:Rat 10:EgyptianMau 11:Hamster
[Pug, Manx, Cymric, Rat, EgyptianMau, Hamster]
*///:~

ListItertor

Iterator 只能向前移動
ListItertor 可以雙向移動,能指向當前位置的前一個和后一個索引,set()方法替換它訪問的過的后一個元素,
listIterator()方法指向開始處, 或用listIterator(n)方法一開始就指向n的索引。

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]
*///:~

LinkedList

執行插入和移除效率較高,不適合隨機訪問


Set

不保存重復的元素
Set中最常被使用的是測試歸屬性,查找是set最重要的操作
Set具有與Collection完全一樣的接口,實際上Set就是Collection,只是行為不用(繼承與多態思想的典型應用:表現不同的行為)


Queue

隊列常被當作一種可靠的將對象從程序的某個區域傳輸到另一個區域的途徑,隊列在并發編程中特別重要

peek() 返回隊頭 隊列為空返回null
element() 返回隊頭 隊列為空拋出異常
poll() 移除并返回隊頭 隊列為空返回null
remove() 移除并返回隊頭 隊列為空拋出異常

PriorityQueue 優先級隊列聲明下一個彈出的元素是最需要的元素(優先級最高的),可用Comparator來設置自己的排序規則


Map

Map和Collection唯一的重疊就是Map可以使用entrySet()和values()方法來產生Collection。


Foreach與迭代器

foreach語法主要用于數組,但它也可以應用于任何Collection對象。實質是任何實現Iterable的類,都可以用foreach

這不意味數組是一個Iterable,把數組當做一個Iterable參數傳遞會導致失敗。說明不存在任何數組到Iterable的自動轉換,必須手動轉換

//: holding/ArrayIsNotIterable.java
import java.util.*;
public class ArrayIsNotIterable {
  static <T> void test(Iterable<T> ib) {
    for(T t : ib)
      System.out.print(t + " ");
  }
  public static void main(String[] args) {
    test(Arrays.asList(1, 2, 3));
    String[] strings = { "A", "B", "C" };
    // An array works in foreach, but it's not Iterable:
    //! test(strings);
    // You must explicitly convert it to an Iterable:
    test(Arrays.asList(strings));
  }
}

/* Output:
1 2 3 A B C
*///:~
*///:~

適配器方法慣用法

向Iterable類添加一個或多種使用foreach的方式
如果直接繼承這個類,并覆蓋iterator()方法。只能替換現有的方法,而不能實現選擇,因此添加一個能夠產生Iterable對象的方法,該對象能夠用于foreach語句

//: holding/MultiIterableClass.java
// Adding several Adapter Methods.
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.
*///:~

注意,第二個方法random()是直接返回被打亂的list中的Iterator。
從輸出中可以看到,Collection.shuffle()方法沒有影響到原來的數組,只是打亂了shuffed中的引用,這是因為用一個Arraylist將Arrays.aslist()方法的結果包裝起來了,如果直接用Arrays.aslist()方法產生,它將會修改底層的數組。因為Arrays.aslist()方法產生list對象會使用底層數組作為其物理實現。
如果不想原來的數組被修改,那就應該在另一個容器創建一個副本。

//: holding/ModifyingArraysAsList.java
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]
*///:~


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,908評論 6 541
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,324評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,018評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,675評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,417評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,783評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,779評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,960評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,522評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,267評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,471評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,009評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,698評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,099評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,386評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,204評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,436評論 2 378

推薦閱讀更多精彩內容

  • java中提供了一套相當完整的集合類,其中基本的類型是List,Set,Queue和Map。 11.1 泛型和類型...
    Lemon_Home閱讀 273評論 0 0
  • 一、基本概念 容器類類庫的用途是保存對象1、Collection:一個獨立元素的序列2、Map:一組成對的“鍵值對...
    whyshang閱讀 188評論 0 0
  • java筆記第一天 == 和 equals ==比較的比較的是兩個變量的值是否相等,對于引用型變量表示的是兩個變量...
    jmychou閱讀 1,511評論 0 3
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,823評論 18 139
  • 概述 Java集合框架由Java類庫的一系列接口、抽象類以及具體實現類組成。我們這里所說的集合就是把一組對象組織到...
    absfree閱讀 1,269評論 0 10