11.1 Lists and Sets

11.1.1 List

之前来说我们已经做好了 AListsSLList

但是我们现在讲用 java 已经内置的 List interface 和 ArrayList

import java.util.List;
import java.util.ArrayList;
 
public class SimpleBuiltInListExample {
  public static void main(String[] args) {
    List<Integer> L = new ArrayList<>();
    L.add(5);
    L.add(10);
    L.add(15);
    System.out.println(L);
  }
}

11.1.2 Set

Set<String> S = new HashSet<>();
S.add("Tokyo");
S.add("Beijing");	
S.add("Lagos");
S.add("São Paulo");
System.out.println(S.contains("Tokyo"));
s = set()
s.add("Tokyo")
s.add("Beijing")
s.add("Lagos")
s.add("São Paulo")
print("Tokyo" in s)

11.2 Exceptions

package lec11_inheritance4;

public class CopyArraySet<T> {
    private T[] items;
    private int size; // the next item to be added will be at position size

    public  CopyArraySet(){
        items = (T[])new Object[100];
        size = 0;
    }
    public  boolean contains(T x) {
        for (int i = 0; i < size; i++) {
            if (items[i].equals(x)) {
                // 注意这里需要写的是 .equals() 而不是 ==
                // why : use == operators for reference comparison (address comparison)
                // and .equals() method for content comparison.
                // In simple words, == checks if both objects point to the same memory location
                // whereas .equals() evaluates to the comparison of values in the objects.
                return true;
            }
        }
        return  false;
    }

    public void add(T x){
        if(contains(x)) return;
        items[size] = x;
        size++;
    }

    public int size(){
        return size;
    }

    public static void main(String[] args) {
        CopyArraySet<String> set = new CopyArraySet<>();
        set.add(null);
        set.add("horse");
        set.add(null);
        set.add("cat");
        set.add("dog");
        System.out.println(set.contains("cat"));
        System.out.println(set.size);
    }
}
public void add(T x){
        if (x == null) {
            throw  new IllegalArgumentException("null");
        }
        if(contains(x)) return;
        items[size] = x;
        size++;
    }

11.3 Iteration

public static void main(String[] args) {
        CopyArraySet<Integer> set = new CopyArraySet<>();
        set.add(1);
        set.add(7);
        set.add(42);

        Set<Integer> set2 = new HashSet<>();
        set2.add(1);
        set2.add(7);
        set2.add(42);

        for ( int i :set2){
            System.out.println(i);
        }
    }

然而我们尝试用 set 来整活:

java: for-each 不适用于表达式类型
  要求: 数组或 java.lang.Iterable
  找到:    lec11_inheritance4.CopyArraySet<java.lang.Integer>

所以我们拆解 for-each :

Set<Integer> javaset =
  new HashSet<Integer>();
...
for (int x : javaset) {
   System.out.println(x);
}
Set<Integer> javaset =
  new HashSet<Integer>();
...
Iterator<Integer> seer
 	= javaset.iterator();
 
while (seer.hasNext()) {
  System.out.println(seer.next());
}