泛型和类型安全的容器
如果想建立一个Appel对象的容器,可以使用ArrayList,可以将ArrarList当作可以自动扩充自身尺寸的一个数组
如何使用ArrayList:创建一个实例,使用add()插入对象,然后用get()方法访问这些对象,这时候就需要使用索引,就像数组一样,但是不需要放扩招,ArrayList还有一个size()方法  (集合中的个数)
class Apple{private static Long count;private final long id = count++;public long id(){return id;}}class Orange{}public class ApplesAndOrangeWithoutGenerics {public static void main(String[] args) {ArrayList apples = new ArrayList(); //没有申明保存的类型,此时保存的就是Object//随意集合里面可以添加Apple类型,也可以添加//Orange类型,但是在取出的时候得到的还是Object//类型,所以需要进行类型转换,但是Orange类型//无法转换成为Apple类型for (int i = 0; i < 3; i++){apples.add(new Apple());}apples.add(new Orange());for (int i = 0 ; i < apples.size();i++){((Apple)apples.get(i)).id(); //orange只有在运行时报错}}}
如果使用泛型就可以在编译器就可以对将错误的类型放到容器中这个错误进行提示
class Apple{private static long count;private final long id = count++;public long id(){return id;}}class Orange{}public class ApplesAndOrangeWithoutGenerics {public static void main(String[] args) {ArrayList<Apple> apples = new ArrayList<Apple>();//指定了集合的类型,此时集合里面//只可以放入Apple类型,否则会报错//并且在取出的时候也不需要类型转换for (int i = 0 ; i < 3; i ++){apples.add(new Apple());}for (int i = 0 ; i < apples.size();i++){System.out.println(apples.get(i).id());}for (Apple c : apples) { //如果不需要每个元素的索引的话,可以使用Foreach来//循环数组中的每个元素System.out.println(c.id());}}}
如果指定了某个类型作为泛型参数的时候,并不是只可以放入该类型的对象,向上转型也可以应用在这里
class GrannySmith extends Apple{}class Gala extends Apple{}class Fuji extends Apple{}class Braeburn extends Apple{}public class GenericsAndUpcasting {public static void main(String[] args) {final ArrayList<Apple> apples = new ArrayList<>();apples.add(new Apple()); //Apple的子类也可以放置容器中apples.add(new Gala());apples.add(new Fuji());apples.add(new Braeburn());for (Apple apple : apples) {System.out.println(apple);}}}
基本概念
(1)Collection:一个独立元素的序列,这些元素都服从一种或者多种规则
①List:必须按照插入的顺序保存元素
②Set:不能有重复的元素
③Queue:按照排队规则来确定对象产生的顺序(通常和被取出的顺序相同)(可能取出之后就不在容器中了)
(2)Map:一组成对的“键值对”对象,允许使用键来查找值,它将数字和对象联系在了一起,映射表允许我们使用另一个对象来查找某个对象,也被称为关联数组
添加一组元素
Array.asList()方法接受一个数组或者是一个用逗号分隔的元素列表(使用可变参数),并且将其转换称为一个List对象
Collections.addAll()方法接受一个Collection对象,以及一个数组或者一个用逗号分隔的列表
public class AddGroups {public static void main(String[] args) {Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));Integer[] moreInt = {6,7,8,9,10};collection.addAll(Arrays.asList(moreInt));Collections.addAll(collection , 11,12,13,14,15);Collections.addAll(collection,moreInt);List<Integer> list = Arrays.asList(16,17,18,19,20);list.set(1,99); // 下标为1的位置改为99}}
Array.asList()底层时数组,无法对其进行add(),delete()方法
容器的打印
public class PrintingContainers {static Collection fill(Collection<String> collection){collection.add("rat");collection.add("cat");collection.add("dog");collection.add("dog");return collection;}static Map fill(Map<String,String> map){map.put("rat","Fuzzy");map.put("cat", "rags");map.put("dog", "Bosco");map.put("dog", "Spot");return map;}public static void main(String[] args) {System.out.println(fill(new ArrayList<String>()));System.out.println(fill(new LinkedList<String>()));System.out.println(fill(new HashSet<String>()));System.out.println(fill(new TreeSet<String>()));System.out.println(fill(new LinkedHashSet<String>()));System.out.println(fill(new HashMap<String,String>()));System.out.println(fill(new TreeMap<String,String>()));System.out.println(fill(new LinkedHashMap<String,String>()));}}
List
ArrayList:随机访问比LinkedList快,但是在中间插入删除元素没有LinkedList快
LinkedList:在List中间插入删除元素比较比ArrayList快,但是在随机访问方面没有ArrayList快
equals:确定一个元素是否属于List,或者发现他的索引,或者从List中移除某个元素,中间都使用的equals
例如两个String对象在完全一样的情况下是相等的,但是如果是自己创建的类的话,如果没有重写的话就算两个类内容相同,但是equals的话也是不想等的
public class ArrayListDemo {public static void main(String[] args) {ArrayList<String> demo = new ArrayList<>();demo.add("haha");demo.add("hehe");demo.add("wuhu");demo.add("xixi");demo.add("asd");demo.add("keke");System.out.println(demo);demo.remove("wuhu");System.out.println(demo);System.out.println(demo.get(2));System.out.println(demo.indexOf("keke"));String s = "sout";System.out.println(demo.indexOf("sout"));System.out.println(demo.remove("sout"));System.out.println(demo.remove("xixi"));System.out.println(demo);demo.add(2,"huwu");System.out.println(demo);List<String> sub =demo.subList(1,4); //左闭右开System.out.println(sub);sub.set(2,"dsa"); //此时更改sub中的参数,demo中的也会被修改System.out.println("sub = " + sub);System.out.println("demo = " + demo); //sub 为 demo的一个视图//是否包含此元素 sub是包含String元素的ListSystem.out.println(demo.contains(sub));System.out.println(demo.containsAll(sub));Collections.sort(sub);System.out.println("Sub = " +sub);System.out.println("demo = " + demo); //更改sub中的参数顺序,demo中的顺序也会改变final Random random = new Random(47);Collections.shuffle(sub,random); //将sub中的参数顺序进行打乱System.out.println(sub);System.out.println(demo);List<String> copy = new ArrayList<String>(demo);System.out.println(demo);System.out.println(copy);sub = Arrays.asList(demo.get(1),demo.get(4));System.out.println(sub);copy.retainAll(sub);System.out.println(copy);copy = new ArrayList<String>(demo);System.out.println(copy);copy.remove(2);System.out.println(copy);copy.removeAll(sub);System.out.println(copy);copy.set(1,"wuhu");System.out.println(sub);copy.addAll(1, sub);System.out.println(copy);System.out.println(demo.isEmpty());demo.clear();demo.add("wuhu");System.out.println(demo);demo.add("haha");demo.add("xixi");demo.add("hehe");demo.add("nene");System.out.println(demo);Object o = demo.toArray();String str = "whuu";int i = 20;System.out.println(str.equals(i));
迭代器
Iterator
首先迭代器是一个对象,它就是用来遍历并选择序列中的对象,迭代器被称为轻量级对象,而且JAVA中的迭代器只能够单项移动。
1 使用方法Iterator()要求容器返回一个Iterator,他将会放回序列的第一个元素
2 使用next()获取下一个元素
3 使用hasnext()来判断是否还有下一个元素
4 使用remove()来将新进返回的元素删除
public class SimpleIteration {public static void main(String[] args) {List<Pet> pets = Pets.arrayList(12);Iterator<Pet> iterator = pets.iterator();while (iterator.hasNext()){Pet p = iterator.next();System.out.print(p.id() + ": " + p + " ");}System.out.println();for (Pet pet : pets) {System.out.print(pet.id() + ": " + pet + " ");}System.out.println();iterator = pets.iterator();for (int i = 0; i < 6; i++) {iterator.next();iterator.remove(); //将新近的元素进行删除}System.out.println(pets);}}
如果只是遍历,foreach也可以,如果想修改里面的元素,可以移除由next()产生的元素
public class CrossContainerIteration {public static void display(Iterator<Pet> iterator){while (iterator.hasNext()){Pet p = iterator.next();System.out.print(p.id() + ": " + p + " ");}System.out.println();}public static void main(String[] args) {ArrayList<Pet> pets = Pets.arrayList(12);LinkedList<Pet> petLinkedList = new LinkedList<>(pets);HashSet<Pet> petHashSet = new HashSet<>(pets);TreeSet<Pet> petTreeSet = new TreeSet<>(pets);LinkedHashSet<Pet> petLinkedHashSet = new LinkedHashSet<>(pets);display(pets.iterator());display(petLinkedList.iterator());display(petHashSet.iterator());display(petTreeSet.iterator());display(petLinkedHashSet.iterator());}}
在display方法中,并没有返回的容器的类型信息,说明:iterator能够将遍历的操作和序列的结构相分离也可以说统一了对容器的访问方式
ListIterator
它是Iterator的一个子类型,它只可以用于List类型的访问,并且它可以双向移动,可以用set来替换它访问过的最后一个元素。
public class ListIteration {public static void main(String[] args) {List<Pet> pets = Pets.arrayList(8);ListIterator<Pet> listIterator = pets.listIterator();while (listIterator.hasNext()){System.out.print(listIterator.next() + ", " +listIterator.nextIndex() + +listIterator.previousIndex() + " ");}System.out.println();while (listIterator.hasPrevious()){System.out.print(listIterator.previous() + ", " +listIterator.previousIndex() + listIterator.nextIndex() + " ");}System.out.println();System.out.println(pets);listIterator = pets.listIterator(3); //从索引为3的位置开始读while (listIterator.hasNext()){listIterator.next();listIterator.set(Pets.randomPet()); //可以边读边改,但是存在并发问题}System.out.println(pets);}}
LinkedList
在执行插入和删除的时候比ArrayList快,但是在随机读取方面没有ArrayList快,并且LinkedList中由让其完成栈,队列或者双端队列的方法。
public class LinkedListFeature {public static void main(String[] args) {LinkedList<Pet> pets = new LinkedList<>(Pets.arrayList(12));System.out.println(pets);System.out.println(pets.getFirst());System.out.println(pets.get(5));System.out.println(pets.element());System.out.println(pets.indexOf(new Cymric()));System.out.println(pets.peek());System.out.println(pets.remove());System.out.println(pets);System.out.println(pets.removeFirst());System.out.println(pets);System.out.println(pets.poll());System.out.println(pets);System.out.println(pets.pollFirst());System.out.println(pets.add(new Rat())); //添加在尾部System.out.println(pets);System.out.println(pets.add(new Mutt()));System.out.println(pets);System.out.println(pets.offer(new Pug()));System.out.println(pets);pets.addLast(new Hamster());System.out.println(pets);System.out.println(pets.removeLast());System.out.println(pets);}}
Set
Set最常被使用于测试归属性,很容易的询问某个对象是否在某个Set中,查找就成了Set中最重要的操作
Set具有和Collectioin完全一样的接口,并没有额外的功能,只是行为有些不同,Set是基于对象的值来判断归属性的
public class SetOfInteger {public static void main(String[] args) {final Random random = new Random(47);Set<Integer> set = new HashSet<>();for (int i = 0; i < 10000; i++) {set.add(random.nextInt(20));}System.out.println(set);}}
如果想对结果进行排序,可以用TreeSet来代替TreeSet
public class SortSetOfInteger {public static void main(String[] args) {TreeSet<Integer> integerTreeSet = new TreeSet<>();Random random = new Random();for (int i = 0; i < 10000; i++) {integerTreeSet.add(random.nextInt(20));}System.out.println(integerTreeSet);}}
Map
一组成对的“键值对”对象,允许使用键来查找值,它将数字和对象联系在了一起,映射表允许我们使用另一个对象来查找某个对象,也被称为关联数组
public class Statistics {public static void main(String[] args) {final Random random = new Random();Map<Integer, Integer> ints = new HashMap<>();for (int i = 0; i < 1000; i++) {int r = random.nextInt(20);Integer freq = ints.get(r);ints.put(r,freq == null ? 1 : freq + 1);}System.out.println(ints);}}
public class PetMap {public static void main(String[] args) {Map<String, Pet> petMap = new HashMap<>();petMap.put("My Cat", new Cat("Molly"));petMap.put("My Dog", new Dog("Ginger"));petMap.put("MyHamster", 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));}}
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> demo = new LinkedList<>();final Random random = new Random(47);for (int i = 0; i < 10; i++) {demo.add(random.nextInt(i + 10));printQ(demo);}Queue<Character> qc = new LinkedList<>();for (char c : "Hello World".toCharArray()) {qc.add(c);}printQ(qc);}}
PriorityQueue
优先级队列,声明下一个弹出的元素是最需要的元素(具有最高的优先级)
当在队列中使用offer来插入一个对象时,这个对象在队列中会被排序,可以提供自己的Comparator来修改这个顺序
public class PriorityDemo {public static void main(String[] args) {PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();final Random random = new Random(47);for (int i = 0; i < 10; i++) {priorityQueue.offer(random.nextInt(i + 10));}printQ(priorityQueue);List<Integer> integers = Arrays.asList(10, 3, 6, 8, 7, 9, 25, 16, 19, 22, 30);PriorityQueue<Integer> integerPriorityQueue = new PriorityQueue<>(integers);printQ(integerPriorityQueue);priorityQueue = new PriorityQueue<>(integers.size(), Collections.reverseOrder());priorityQueue.addAll(integers);printQ(priorityQueue);String str = "w a n g b o t a o s h i g e d a s h a b i ";List<String> strings = Arrays.asList(str.split(" "));PriorityQueue<String> stringPriorityQueue = new PriorityQueue<>(strings);printQ(stringPriorityQueue);stringPriorityQueue = new PriorityQueue<>(strings.size(), Collections.reverseOrder());stringPriorityQueue.addAll(strings);printQ(stringPriorityQueue);Set<Character> characters = new HashSet<>(); //消除重复的字母,Set中不可以有重复的for (char c : str.toCharArray()) {characters.add(c);}PriorityQueue<Character> characterPriorityQueue = new PriorityQueue<>(characters);printQ(characterPriorityQueue);}}
允许重复,并且值越小优先级越高,在String中,空格也有值,并且它的优先级比字母小
Collection和Iterator
首先,Collection时描述所有序列的根接口,因为要表示其他若干个接口的共性而出现的接口
public class InterfaceVsIterator {public static void display(Iterator<Pet> iterator){while (iterator.hasNext()){Pet p = iterator.next();System.out.print(p.id() + ": " + p + " ");}System.out.println();}public static void display(Collection<Pet> collection){for (Pet pet : collection) {System.out.print(pet.id() + ": " + pet + " ");}System.out.println();}public static void main(String[] args) {List<Pet> petList = Pets.arrayList(10);Set<Pet> petHashSet = new HashSet<>(petList);Set<Pet> petsTreeSet = new TreeSet<>(petList);Map<String,Pet> petMap = new LinkedHashMap<>();String[] names = {"wh", "wgx", "wbt", "wgy", "ssn", "zmy", "hah", "wuhu", "hehe", "xixi"};for (int i = 0; i < names.length; i++) {petMap.put(names[i], petList.get(i));}display(petList);display(petHashSet);display(petsTreeSet);display(petList.iterator());display(petHashSet.iterator());display(petsTreeSet.iterator());System.out.println(petMap);System.out.println(petMap.keySet());display(petMap.values());display(petMap.values().iterator());}
public class CollectionSequence extends AbstractCollection<Pet> {private Pet[] pets = Pets.createArray(8);@Overridepublic Iterator<Pet> iterator() {return new Iterator<Pet>() {private int index = 0;@Overridepublic boolean hasNext() {return index < pets.length;}@Overridepublic Pet next() {return pets[index++];}};}@Overridepublic int size() {return pets.length;}public static void main(String[] args) {final CollectionSequence pets = new CollectionSequence();display(pets);display(pets.iterator());}}
Foreach和迭代器
foreach应用于数组,并且可以应用于所有的Collection对象
public class ForeachCollection {public static void main(String[] args) {Collection<String> strings = new LinkedList<>();Collections.addAll(strings, "Take me Way Home".split(""));for (String string : strings) {System.out.print(string);}}
适配器的惯用法
必须提供特定的接口以满足foreach语句,当有一个接口,并且需要另外一个接口的时候,可以编写适配器
class ReversibleArrayList<T> extends ArrayList<T>{public ReversibleArrayList(Collection<T> c){super(c);}public Iterable<T> reversed(){return new Iterable<T>() {@Overridepublic Iterator<T> iterator() {return new Iterator<T>() {int current = size()-1;@Overridepublic boolean hasNext() {return current > -1;}@Overridepublic T next() {return get(current--);}};}};}}public class AdapterMethodIdiom {public static void main(String[] args) {ReversibleArrayList<String> strings = new ReversibleArrayList<String>(Arrays.asList("To Be Or Not To Be".split(" ")));for (String string : strings) {System.out.print(string);}System.out.println();for (String s : strings.reversed()) {System.out.print(s);}}}
