《Java编程思想》第十一章 持有对象
Posted zlz099
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《Java编程思想》第十一章 持有对象相关的知识,希望对你有一定的参考价值。
1、数组时保存一组对象的最有效方式。如保存一组基本数据类型,但数组有固定的尺寸。
2、Collection表示集合类的一个特殊子集。
List必须按照插入的顺序保存元素,
Queue按照排队规则定义元素的产生的顺序(通常与插入顺序相同)。
Set每个值只存储一个对象,
Map允许将某些对象与其他一些对象关联起来的关联数组。
3、ArrayList创建一个实例,用add()插入对象,get()访问对象。size()知道存了多少元素。随机访问元素。但插入和移动元素慢。
LinkedList方便插入删除,优化的顺序访问,但随机访问较慢。
4、通过使用泛型可以在编译器防止将错误的类型的对象存放在容器中。
5、当指定了某个类型作为泛型参数时,不仅限于只能将该确切类型的对象放置到容器中。
6、Array.asList()接受一个数组或者一个用逗号分隔的元素列表并将其转换成一个List对象。
Collection.addAll()接收一个Collection对象,以及一个逗号分隔的列表,将元素添加在collection中。
7、HashSet最快的方式获取元素。散列函数
TreeSet存储顺序。按比较结果的升序保存键。红-黑树
LinkedHashSet按照添加的顺序保存对象,保留了HashMap的查询速度。
8、Map尺寸会自动调整。Map每个键只存储一次。键和值在Map中存储的顺序不是他们的插入顺序。
9、List中 contains()方法确定某个对象是否存在在列表中。
remove()方法移除对象
indexOf()方法查询对象在List中的位置
subList()允许很容易的从较大的列表中创建出一个片段。这个结果传递给containsAll()方法时,必然是true
retainAll()方法有效的交集操作
removeAll()移除list中所有元素
toArray()方法将任意Collection转换成一个数组
与Pet包相关的:
1 package pets; 2 /** 3 * @author zlz099: 4 * @version 创建时间:2017年9月29日 上午10:37:12 5 */ 6 public class Pet extends Individual{ 7 public Pet(String name){ 8 super(name); 9 } 10 public Pet(){super();} 11 }
1 package pets; 2 3 import java.util.*; 4 5 /** 6 * @author zlz099: 7 * @version 创建时间:2017年9月29日 下午4:26:29 8 */ 9 public class PetCount { 10 static class PetCounter extends HashMap<String,Integer>{ 11 public void count(String type){ 12 Integer quantity = get(type); 13 if(quantity == null) 14 put(type, 1); 15 else { 16 put(type, quantity+1); 17 } 18 } 19 } 20 public static void countPets(PetCreator creator){ 21 PetCounter counter = new PetCounter(); 22 for(Pet pet :creator.createArray(20)){ 23 System.out.println(pet.getClass().getSimpleName()+" "); 24 if(pet instanceof Pet) 25 counter.count("Pet"); 26 if(pet instanceof Dog) 27 counter.count("Dog"); 28 if(pet instanceof Mutt) 29 counter.count("Mutt"); 30 if(pet instanceof Pug) 31 counter.count("Pug"); 32 if(pet instanceof Cat) 33 counter.count("Cat"); 34 if(pet instanceof Manx) 35 counter.count("EgyptianMau"); 36 if(pet instanceof Manx) 37 counter.count("Manx"); 38 if(pet instanceof Manx) 39 counter.count("Cymric"); 40 if(pet instanceof Rodent) 41 counter.count("Rodent"); 42 if(pet instanceof Rat) 43 counter.count("Rat"); 44 if(pet instanceof Mouse) 45 counter.count("Mouse"); 46 if(pet instanceof Hamster) 47 counter.count("Hamster"); 48 } 49 System.out.println(); 50 System.out.println(counter); 51 } 52 public static void main(String[] args) { 53 // TODO Auto-generated method stub 54 countPets(new ForNameCreator()); 55 } 56 57 }
1 package pets; 2 3 import java.util.*; 4 5 /** 6 * @author zlz099: 7 * @version 创建时间:2017年9月29日 上午10:47:13 8 */ 9 public abstract class PetCreator { 10 private Random rand = new Random(47); 11 public abstract List<Class<?extends Pet>> types(); 12 public Pet randomPet(){ 13 int n = rand.nextInt(types().size()); 14 try { 15 return types().get(n).newInstance(); 16 } catch (InstantiationException e) { 17 // TODO: handle exception 18 throw new RuntimeException(e); 19 }catch (IllegalAccessException e) { 20 // TODO: handle exception 21 throw new RuntimeException(e); 22 } 23 } 24 public Pet[] createArray(int size){ 25 Pet[] result = new Pet[size]; 26 for(int i = 0; i< size; i++) 27 result[i] = randomPet(); 28 return result; 29 } 30 public ArrayList<Pet> arrayList(int size){ 31 ArrayList<Pet> result = new ArrayList<Pet>(); 32 Collections.addAll(result, createArray(size)); 33 return result; 34 } 35 }
1 package pets; 2 3 import java.util.*; 4 5 /** 6 * @author zlz099: 7 * @version 创建时间:2017年9月29日 上午10:57:34 8 */ 9 public class ForNameCreator extends PetCreator{ 10 11 private static List<Class<? extends Pet>> types = new ArrayList<Class<? extends Pet>>(); 12 private static String[] typeNames = { 13 "typeinfo.Pets.Mutt", 14 "typeinfo.Pets.Pug", 15 "typeinfo.Pets.EgyptianMau", 16 "typeinfo.Pets.Manx", 17 "typeinfo.Pets.Cumric", 18 "typeinfo.Pets.Rat", 19 "typeinfo.Pets.Mouse", 20 "typeinfo.Pets.Hamster" 21 }; 22 @SuppressWarnings("unchecked") 23 private static void loader(){ 24 try { 25 for(String name : typeNames) 26 types.add((Class<? extends Pet>)Class.forName(name)); 27 } catch (ClassNotFoundException e) { 28 // TODO: handle exception 29 throw new RuntimeException(e); 30 } 31 } 32 static {loader();} 33 @Override 34 public List<Class<? extends Pet>> types() { 35 // TODO Auto-generated method stub 36 return types; 37 } 38 39 }
1 package pets; 2 3 import java.util.*; 4 5 /** 6 * @author zlz099: 7 * @version 创建时间:2017年9月29日 上午10:57:34 8 */ 9 public class ForNameCreator extends PetCreator{ 10 11 private static List<Class<? extends Pet>> types = new ArrayList<Class<? extends Pet>>(); 12 private static String[] typeNames = { 13 "typeinfo.Pets.Mutt", 14 "typeinfo.Pets.Pug", 15 "typeinfo.Pets.EgyptianMau", 16 "typeinfo.Pets.Manx", 17 "typeinfo.Pets.Cumric", 18 "typeinfo.Pets.Rat", 19 "typeinfo.Pets.Mouse", 20 "typeinfo.Pets.Hamster" 21 }; 22 @SuppressWarnings("unchecked") 23 private static void loader(){ 24 try { 25 for(String name : typeNames) 26 types.add((Class<? extends Pet>)Class.forName(name)); 27 } catch (ClassNotFoundException e) { 28 // TODO: handle exception 29 throw new RuntimeException(e); 30 } 31 } 32 static {loader();} 33 @Override 34 public List<Class<? extends Pet>> types() { 35 // TODO Auto-generated method stub 36 return types; 37 } 38 39 }
1 package pets; 2 /** 3 * @author zlz099: 4 * @version 创建时间:2017年9月29日 上午10:21:44 5 */ 6 public class Individual implements Comparable<Individual>{ 7 8 private static long counter = 0; 9 private final long id = counter++; 10 private String name; 11 public Individual(String name){this.name = name;} 12 public Individual(){} 13 public String toString(){return getClass().getSimpleName()+(name == null?"":" "+name);} 14 public long id(){return id;} 15 public boolean equals(Object o){return o instanceof Individual && id ==((Individual)o).id;} 16 public int hashCode(){ 17 int result = 17; 18 if(name != null) 19 result = 37*result+name.hashCode(); 20 result = 37*result + (int)id; 21 return result; 22 } 23 @Override 24 public int compareTo(Individual arg) { 25 // TODO Auto-generated method stub 26 String first = getClass().getSimpleName(); 27 String argFirst = arg.getClass().getSimpleName(); 28 int firstCompare = first.compareTo(argFirst); 29 if(firstCompare != 0) 30 return firstCompare; 31 if(name != null && arg.name!=null){ 32 int secondCompare = name.compareTo(arg.name); 33 if(secondCompare!=0) 34 return secondCompare; 35 } 36 return (arg.id<id?-1:(arg.id == id?0:1)); 37 } 38 39 }
1 package pets; 2 /** 3 * @author zlz099: 4 * @version 创建时间:2017年9月29日 上午10:21:44 5 */ 6 public class Individual implements Comparable<Individual>{ 7 8 private static long counter = 0; 9 private final long id = counter++; 10 private String name; 11 public Individual(String name){this.name = name;} 12 public Individual(){} 13 public String toString(){return getClass().getSimpleName()+(name == null?"":" "+name);} 14 public long id(){return id;} 15 public boolean equals(Object o){return o instanceof Individual && id ==((Individual)o).id;} 16 public int hashCode(){ 17 int result = 17; 18 if(name != null) 19 result = 37*result+name.hashCode(); 20 result = 37*result + (int)id; 21 return result; 22 } 23 @Override 24 public int compareTo(Individual arg) { 25 // TODO Auto-generated method stub 26 String first = getClass().getSimpleName(); 27 String argFirst = arg.getClass().getSimpleName(); 28 int firstCompare = first.compareTo(argFirst); 29 if(firstCompare != 0) 30 return firstCompare; 31 if(name != null && arg.name!=null){ 32 int secondCompare = name.compareTo(arg.name); 33 if(secondCompare!=0) 34 return secondCompare; 35 } 36 return (arg.id<id?-1:(arg.id == id?0:1)); 37 } 38 39 }
1 package pets; 2 3 import java.util.List; 4 import java.io.ObjectOutputStream.PutField; 5 import java.util.Arrays; 6 import java.util.Collections; 7 8 /** 9 * @author zlz099: 10 * @version 创建时间:2017年9月29日 下午4:53:45 11 */ 12 public class LiteralPetCreator extends PetCreator{ 13 @SuppressWarnings("unchecked") 14 public static final List<Class<? extends Pet>> allTypes = Collections.unmodifiableList(Arrays.asList( 15 Pet.class,Dog.class,Cat.class,Rodent.class,Mutt.class,Pug.class,EgyptianMau.class, 16 Manx.class,Cymric.class,Rat.class,Mouse.class,Hamster.class 17 )); 18 private static final List<Class<? extends Pet>> types = 19 allTypes.subList(allTypes.indexOf(Mutt.class),allTypes.size()); 20 public List<Class<? extends Pet>> types(){ 21 return types; 22 } 23 public static void main(String[] args) { 24 // TODO Auto-generated method stub 25 System.out.println(types); 26 } 27 28 }
10、迭代器是一个对象,遍历并选择序列中的对象,Iterator只能单向移动,只能用来:
1)使用方法iterator()要求容器返回一个Iterator,将准备好返回第一个元素
2)使用next()获得下一个元素
3)使用hasNext()检查是否还有元素
4)使用remove()将迭代器新近返回元素删除
11、display()方法不包含任何和它所遍历的序列的类型信息。这表示Iterator能将遍历序列的操作与序列底层的结构分离。
12、Set常用来测试归属性。基于对象的值确定归属性。
13、Map可以扩展到多维,只需将他的值设置成Map。因此可以很容易把容器组合起来快速生成强大的数据结构。
14、Queue先进先出。offer()讲一个元素插入到队尾或者返回false()
peek()和element()都在不移除的情况下返回队头。peek在空时返回null,element返回NoSuchElementExcption异常。
poll()和remove()移除并返回队头。
15、PriorityQueue声明下一个弹出的元素是最需要的元素,即优先级最高的元素。offer插入一个元素时即在队列中排序。调用peek,poll,remove时,获取的都是队列中优先级最高的元素。
重复是允许的,最小的值拥有最高优先级(String的话,空格也算值,并比字母优先级高)
16、foreach主要用于数组,但也可以用于任何Collection对象
1 import java.util.ArrayList; 2 import java.util.Arrays; 3 import java.util.Collection; 4 import java.util.Iterator; 5 6 /** 7 * @author zlz099: 8 * @version 创建时间:2017年10月12日 下午5:29:30 9 */ 10 class ReversibleArrayList<T> extends ArrayList<T>{ 11 public ReversibleArrayList(Collection<T> c){super(c);} 12 public Iterable<T> reversed(){ 13 return new Iterable<T>() { 14 public Iterator<T> iterator() { 15 return new Iterator<T>(){ 16 int current = size()-1; 17 public boolean hasNext(){return current>-1;} 18 public T next(){return get(current--);} 19 public void remove(){throw new UnsupportedOperationException();} 20 }; 21 } 22 }; 23 } 24 } 25 public class AdapterMethodIdiom { 26 27 public static void main(String[] args) { 28 // TODO Auto-generated method stub 29 ReversibleArrayList<String> ral = new ReversibleArrayList<String>(Arrays.asList("To be or not to be".split(" "))); 30 for(String s : ral) 31 System.out.print(s+" "); 32 System.out.println(); 33 for(String s : ral.reversed()) 34 System.out.print(s+" "); 35 } 36 37 }
1 import java.util.*; 2 /** 3 * @author zlz099: 4 * @version 创建时间:2017年9月28日 上午10:36:38 5 */ 6 public class AddingGroups { 7 8 public static void main(String[] args) { 9 // TODO Auto-generated method stub 10 Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5)); 11 System.out.println(collection); 12 Integer[] moreInts = {6,7,8,9,10}; 13 collection.addAll(Arrays.asList(moreInts)); 14 System.out.println(collection); 15 Collections.addAll(collection, 11,12,13,14,15); 16 System.out.println(collection); 17 Collections.addAll(collection, moreInts); 18 System.out.println(collection); 19 List<Integer> list = Arrays.asList(16,17,18,19,20); 20 System.out.println(list); 21 list.set(1, 99); 22 System.out.println(list); 23 //list.add(11); 24 //System.out.println(list); 不能进行delete和add操作,因为底层表示的是数组。 25 } 26 27 }
1 import java.util.ArrayList; 2 3 /** 4 * @author zlz099: 5 * @version 创建时间:2017年9月27日 下午9:56:43 6 * generic 商标 7 */ 8 class Apple{ 9 private static long counter; 10 private final long id = counter++; 11 public long id(){return id;} 12 } 13 14 class Orange{} 15 16 public class ApplesAndOrangesWithoutGenerics { 17 @SuppressWarnings("unckecks") 18 public static void main(String[] args){ 19 ArrayList<Apple> apples = new ArrayList<Apple>(); 20 for(int i = 0; i< 3; i++) 21 apples.add(new Apple()); 22 //apples.add(new Orange()); 编译时出错,编译器阻止将Orange放入Apple 23 for(int i = 0 ; i<apples.size();i++) 24 //((Apple)apples.get(i)).id(); 25 System.out.println(((Apple)apples.get(i)).id()); 26 for(Apple c : apples) 27 System.out.println(c.id()); 28 } 29 }
1 import java.util.Arrays; 2 3 /** 4 * @author zlz099: 5 * @version 创建时间:2017年10月12日 下午5:09:11 6 */ 7 public class ArrayIsNotIterable { 8 static <T> void test(Iterable<T> ib){ 9 for(T t : ib) 10 System.out.print(t+" "); 11 } 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 test(Arrays.asList(1,2,3)); 15 String[] strings = {"A","B","C"}; 16 test(Arrays.asList(strings)); 17 } 18 19 }
1 import java.util.ArrayList; 2 import java.util.Collections; 3 import java.util.List; 4 import java.util.Arrays; 5 6 /** 7 * @author zlz099: 8 * @version 创建时间:2017年9月28日 上午10:52:56 9 */ 10 class Snow{} 11 class Power extends Snow{} 12 class Light extends Power{} 13 class Heavy extends Power{} 14 class Crusty extends Snow{} 15 class Slush extends Snow{} 16 public class AsListInterface { 17 18 public static void main(String[] args) { 19 // TODO Auto-generated method stub 20 List<Snow> snow1 = Arrays.asList(new Crusty(),new Slush(),new Power()); 21 List<Snow> snow3 = new ArrayList<Snow>(); 22 Collections.addAll(snow3,new Light(),new Heavy()); 23 List<Snow> snow4 = Arrays.<Snow>asList(new Light(),new Heavy()); 24 System.out.println(snow1); 25 System.out.println(snow3); 26 System.out.println(snow4); 27 } 28 29 }
1 import java.nio.channels.UnsupportedAddressTypeException; 2 import java.util.AbstractCollection; 3 import java.util.Iterator; 4 5 import pets.*; 6 7 /** 8 * @author zlz099: 9 * @version 创建时间:2017年10月11日 下午4:08:32 10 * @param <E> 11 */ 12 public class CollectionSequence extends AbstractCollection<Pet>{ 13 private Pet[] pets = Pets.createArray(8); 14 public int size() { 15 // TODO Auto-generated method stub 16 return pets.length; 17 } 18 public Iterator<Pet> iterator() { 19 // TODO Auto-generated method stub 20 return new Iterator<Pet>() { 21 private int index = 0; 22 public boolean hasNext(){ 23 return index < pets.length; 24 } 25 public Pet next(){return pets[index++];} 26 public void remove(){throw new UnsupportedOperationException();} 27 }; 28 } 29 public static void main(String[] args) { 30 // TODO Auto-generated method stub 31 CollectionSequence c = new CollectionSequence(); 32 InterfaceVsIterator.display(c); 33 InterfaceVsIterator.display(c.iterator()); 34 } 35 }
1 import java.nio.channels.UnsupportedAddressTypeException; 2 import java.util.AbstractCollection; 3 import java.util.Iterator; 4 5 import pets.*; 6 7 /** 8 * @author zlz099: 9 * @version 创建时间:2017年10月11日 下午4:08:32 10 * @param <E> 11 */ 12 public class CollectionSequence extends AbstractCollection<Pet>{ 13 private Pet[] pets = Pets.createArray(8); 14 public int size() { 15 // TODO Auto-generated method stub 16 return pets.length; 17 } 18 public Iterator<Pet> iterator() { 19 // TODO Auto-generated method stub 20 return new Iterator<Pet>() { 21 private int index = 0; 22 public boolean hasNext(){ 23 return index < pets.length; 24 } 25 public Pet next(){return pets[index++];} 26 public void remove(){throw new UnsupportedOperationException();} 27 }; 28 } 29 public static void main(String[] args) { 30 // TODO Auto-generated method stub 31 CollectionSequence c = new CollectionSequence(); 32 InterfaceVsIterator.display(c); 33 InterfaceVsIterator.display(c.iterator()); 34 } 35 }
1 import java.util.ArrayList; 2 import java.util.HashSet; 3 import java.util.Iterator; 4 import java.util.LinkedList; 5 import java.util.TreeSet; 6 7 import pets.*; 8 9 10 /** 11 * @author zlz099: 12 * @version 创建时间:2017年10月9日 上午11:25:06 13 */ 14 public class CrossContainerIteration { 15 16 public static void display(Iterator<Pet> it){ 17 while(it.hasNext()){ 18 Pet p = it.next(); 19 System.out.print(p.id()+":"+p+" "); 20 } 21 System.out.println(); 22 } 23 public static void main(String[] args) { 24 // TODO Auto-generated method stub 25 ArrayList<Pet> pets = Pets.arrayList(8); 26 LinkedList<Pet> petsLL = new LinkedList<Pet>(pets); 27 HashSet<Pet> petsHS = new HashSet<Pet>(pets); 28 TreeSet<Pet> petsTS = new TreeSet<Pet>(pets); 29 30 display(pets.iterator()); 31 display(petsLL.iterator()); 32 display(petsHS.iterator()); 33 display(petsTS.iterator()); 34 } 35 36 }
1 import java.util.Map; 2 3 /** 4 * @author zlz099: 5 * @version 创建时间:2017年10月11日 下午5:18:58 6 */ 7 public class EnvironmentVariables { 8 9 public static void main(String[] args) { 10 // TODO Auto-generated method stub 11 for(Map.Entry entry : System.getenv().entrySet()){ 12 System.out.println(entry.getKey()+": "+entry.getValue()); 13 } 14 } 15 }
1 import java.util.Map; 2 3 /** 4 * @author zlz099: 5 * @version 创建时间:2017年10月11日 下午5:18:58 6 */ 7 public class EnvironmentVariables { 8 9 public static void main(String[] args) { 10 // TODO Auto-generated method stub 11 for(Map.Entry entry : System.getenv().entrySet()){ 12 System.out.println(entry.getKey()+": "+entry.getValue()); 13 } 14 } 15 }
1 import java.util.*; 2 3 import pets.*; 4 5 /** 6 * @author zlz099: 7 * @version 创建时间:2017年10月11日 下午3:50:10 8 */ 9 public class InterfaceVsIterator { 10 11 public static void display(Iterator<Pet> it){ 12 while(it.hasNext()){ 13 Pet p = it.next(); 14 System.out.print(p.id()+":"+p+" "); 15 } 16 System.out.println(); 17 } 18 public static void display(Collection<Pet> pets){ 19 for(Pet p: pets) 20 System.out.print(p.id()+":"+p+" "); 21 System.out.println(); 22 } 23 public static void main(String[] args) { 24 // TODO Auto-generated method stub 25 List<Pet> petList = Pets.arrayList(8); 26 Set<Pet> petSet = new HashSet<Pet>(petList); 27 Map<String, Pet> petMap = new LinkedHashMap<String,Pet>(); 28 String[] names = ("Ralph,Eric,Robin,Lcaey, "+"Britney,Sam,Spot,Fluffy").split(","); 29 for(int i = 0; i < names.length; i++) 30 petMap.put(names[i], petList.get(i)); 31 display(petList); 32 display(petSet); 33 display(petList.iterator()); 34 display(petSet.iterator()); 35 System.out.println(petMap); 36 System.out.println(petMap.keySet()); 37 display(petMap.values()); 38 display(petMap.values().iterator()); 39 40 } 41 42 }
1 import java.util.*; 2 3 import pets.*; 4 5 /** 6 * @author zlz099: 7 * @version 创建时间:2017年10月11日 下午3:50:10 8 */ 9 public class InterfaceVsIterator { 10 11 public static void display(Iterator<Pet> it){ 12 while(it.hasNext()){ 13 Pet p = it.next(); 14 System.out.print(p.id()+":"+p+" "); 15 } 16 System.out.println(); 17 } 18 public static void display(Collection<Pet> pets){ 19 for(Pet p: pets) 20 System.out.print(p.id()+":"+p+" "); 21 System.out.println(); 22 } 23 public static void main(String[] args) { 24 // TODO Auto-generated method stub 25 List<Pet> petList = Pets.arrayList(8); 26 Set<Pet> petSet = new HashSet<Pet>(petList); 27 Map<String, Pet> petMap = new LinkedHashMap<String,Pet>(); 28 String[] names = ("Ralph,Eric,Robin,Lcaey, "+"Britney,Sam,Spot,Fluffy").split(","); 29 for(int i = 0; i < names.length; i++) 30 petMap.put(names[i], petList.get(i)); 31 display(petList); 32 display(petSet); 33 display(petList.iterator()); 34 display(petSet.iterator()); 35 System.out.println(petMap); 36 System.out.println(petMap.keySet()); 37 display(petMap.values()); 38 display(petMap.values().iterator()); 39 40 } 41 42 }
1 import java.util.Iterator; 2 3 /** 4 * @author zlz099: 5 * @version 创建时间:2017年10月12日 下午9:32:39 6 */ 7 public class IterableClass implements Iterable<String>{ 8 protected String[] words = ("And that is how "+ "we know the Earth to be banana-shaped.").split(" "); 9 10 public Iterator<String> iterator() { 11 // TODO Auto-generated method stub 12 return new Iterator<String>() { 13 private int index = 0; 14 public boolean hasNext(){ 15 return index < words.length; 16 } 17 public String next(){return words[index++];} 18 public void remove(){throw new UnsupportedOperationException();} 19 }; 20 } 21 22 public static void main(String[] args){ 23 for(String s : new IterableClass()) 24 System.out.print(s+" "); 25 } 26 }
1 import java.util.LinkedList; 2 3 import pets.*; 4 5 /** 6 * @author zlz099: 7 * @version 创建时间:2017年10月9日 下午9:25:28 8 */ 9 public class LinkedListFeatures { 10 11 public static void main(String[] args) { 12 // TODO Auto-generated method stub 13 LinkedList<Pet> pets = new LinkedList<Pet>(Pets.arrayList(5)); 14 System.out.print(pets); 15 System.out.print("pets.getFirst(): "+pets.getFirst()); 16 System.out.print("pets.element(): "+pets.element()); 17 System.out.print("pets.peek(): "+pets.peek()); 18 System.out.print("pets.remove(): "+pets.remove()); 19 System.out.print("pets.removeFirst(): "+pets.removeFirst()); 20 System.out.print("pets.poll(): "+pets.poll()); 21 System.out.print(pets); 22 pets.addFirst(new Rat()); 23 System.out.print("After Add First(): "+pets); 24 25 pets.offer(Pets.randomPet()); 26 System.out.print("After Offer(): "+pets); 27 pets.add(Pets.randomPet()); 28 29 System.out.print("After add(): "+pets); 30 pets.addLast(new Hamster()); 31 System.out.print("After addLast(): "+pets); 32 System.out.print("pets.removeLast(): "+pets.removeLast()); 33 } 34 }
1 /** 2 * @author zlz099: 3 * @version 创建时间:2017年9月28日 下午3:40:31 4 */ 5 import pets.*; 6 7 import java.util.*; 8 public class ListFeature { 9 10 public static void main(String[] args) { 11 // TODO Auto-generated method stub 12 Random rand = new Random(47); 13 List<Pet>pets = Pets.arrayList(7); 14 System.out.println("1: " + pets); 15 Hamster h = new Hamster(); 16 pets.add(h); 17 System.out.println("2: "+pets); 18 System.out.println("3: "+pets.contains(h)); //contains()方法确定某个对象是否在列表中 19 pets.remove(h); //remove()方法移除一个对象 20 Pet p = pets.get(2); 21 System.out.println("4: "+p+" "+pets.indexOf(p)); //indexof()方法发现该对象在List中所处的位置 22 Pet cymric = new Cymric(); 23 System.out.println("5: "+pets.indexOf(cymric)); 24 System.out.println("6: "+pets.remove(cymric)); 25 System.out.println("7: "+pets.remove(p)); 26 System.out.println("8: "+pets); 27 pets.add(3,new Mouse()); 28 System.out.println("9: "+pets); 29 List<Pet> sub = pets.subList(1, 4); //subList()方法允许从较大的列表中创建一个新的片段 这个片段传入containsAll()中肯定是true 30 System.out.println("subList: "+sub); 31 System.out.println("10: "+pets.containsAll(sub)); 32 Collections.sort(sub); 33 System.out.println("sorted subList: "+sub); 34 System.out.println("11: "+pets.containsAll(sub)); 35 Collections.shuffle(sub,rand); 36 System.out.println("12: "+pets.containsAll(sub)); 37 List<Pet> copy = new ArrayList<Pet>(pets); 38 sub = Arrays.asList(pets.get(1),pets.get(4)); 39 System.out.println("sub: "+sub); 40 copy.retainAll(sub); //retainAll()是一种交集操作 同时保留copy和sub中的元素 41 System.out.println("13: "+copy); 42 copy = new ArrayList<Pet>(pets); 43 copy.remove(2); 44 System.out.println("14: "+copy); 45 copy.removeAll(sub); //removeAll()也是基于equals的,从List中删除所有的元素 46 System.out.println("15: "+copy); 47 copy.set(1, new Mouse()); 48 System.out.println("16: "+copy); 49 copy.addAll(2,sub); 50 System.out.println("17: "+copy); 51 System.out.println("18: "+pets.isEmpty()); 52 pets.clear(); 53 System.out.println("19: "+pets); 54 System.out.println("20: "+pets.isEmpty()); //isEmpty和clear方法 55 pets.addAll(Pets.arrayList(4)); 56 System.out.println("21: "+pets); 57 Object[] o = pets.toArray(); 58 System.out.println("22: "+o[3]); 59 Pet[] pa = pets.toArray(new Pet[0]); //toArray()方法将任意的Collection转化为一个数组 60 System.out.println("23: "+pa[3].id()); 61 62 } 63 64 }
1 /** 2 * @author zlz099: 3 * @version 创建时间:2017年9月28日 下午3:40:31 4 */ 5 import pets.*; 6 7 import java.util.*; 8 public class ListFeature { 9 10 public static void main(String[] args) { 11 // TODO Auto-generated method stub 12 Random rand = new Random(47); 13 List<Pet>pets = Pets.arrayList(7); 14 System.out.println("1: " + pets); 15 Hamster h = new Hamster(); 16 pets.add(h); 17 System.out.println("2: "+pets); 18 System.out.println("3: "+pets.contains(h)); //contains()方法确定某个对象是否在列表中 19 pets.remove(h); //remove()方法移除一个对象 20 Pet p = pets.get(2); 21 System.out.println("4: "+p+" "+pets.indexOf(p)); //indexof()方法发现该对象在List中所处的位置 22 Pet cymric = new Cymric(); 23 System.out.println("5: "+pets.indexOf(cymric)); 24 System.out.println("6: "+pets.remove(cymric)); 25 System.out.println("7: "+pets.remove(p)); 26 System.out.println("8: "+pets); 27 pets.add(3,new Mouse()); 28 System.out.println("9: "+pets); 29 List<Pet> sub = pets.subList(1, 4); //subList()方法允许从较大的列表中创建一个新的片段 这个片段传入containsAll()中肯定是true 30 System.out.println("subList: "+sub); 31 System.out.println("10: "+pets.containsAll(sub)); 32 Collections.sort(sub); 33 System.out.println("sorted subList: "+sub); 34 System.out.println("11: "+pets.containsAll(sub)); 35 Collections.shuffle(sub,rand); 36 System.out.println("12: "+pets.containsAll(sub)); 37 List<Pet> copy = new ArrayList<Pet>(pets); 38 sub = Arrays.asList(pets.get(1),pets.get(4)); 39 System.out.println("sub: "+sub); 40 copy.retainAll(sub); //retainAll()是一种交集操作 同时保留copy和sub中的元素 41 System.out.println("13: "+copy); 42 copy = new ArrayList<Pet>(pets); 43 copy.remove(2); 44 System.out.println("14: "+copy); 45 copy.removeAll(sub); //removeAll()也是基于equals的,从List中删除所有的元素 46 System.out.println("15: "+copy); 47 copy.set(1, new Mouse()); 48 System.out.println("16: "+copy); 49 copy.addAll(2,sub); 50 System.out.println("17: "+copy); 51 System.out.println("18: "+pets.isEmpty()); 52 pets.clear(); 53 System.out.println("19: "+pets); 54 System.out.println("20: "+pets.isEmpty()); //isEmpty和clear方法 55 pets.addAll(Pets.arrayList(4)); 56 System.out.println("21: "+pets); 57 Object[] o = pets.toArray(); 58 System.out.println("22: "+o[3]); 59 Pet[] pa = pets.toArray(new Pet[0]); //toArray()方法将任意的Collection转化为一个数组 60 System.out.println("23: "+pa[3].id()); 61 62 } 63 64 }
import java.util.List; import java.util.ListIterator; import pets.*; /** * @author zlz099: * @version 创建时间:2017年10月9日 下午9:15:41 */ public class ListIteration { public static void main(String[] args) { // TODO Auto-generated method stub List<Pet> pets = Pets.arrayList(8); ListIterator<Pet> it = pets.listIterator(); while(it.hasNext()) System.out.println(it.next() + ", "+it.nextIndex()+", "+it.previousIndex()+"; "); System.out.println(); 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); } }
import pets.*; import java.util.*; /** * @author zlz099: * @version 创建时间:2017年10月11日 上午11:12:10 */ public class MapOfList { public static Map<Person, List<? extends Pet>> petPeople = new HashMap<Person, List<? extends Pet>>(); static { petPeople.put(new Person("Dawn"), Arrays.asList(new Cymric("Holly"),new Mutt("Spot"))); petPeople.put(new Person("Kate"), Arrays.asList(new Cat("Shackleton"), new Cat("Elsie May"),new Dog("Margrett"))); petPeople.put(new Person("Marilyn"), Arrays.asList(new Pug("Louie aka Louis Snorkelstein Dupree"), new Cat("Stanford aka Stinky el Negro"), new Cat("Prinkola"))); petPeople.put(new Person("Luke"), Arrays.asList(new Rat("Fussy"),new Rat("Fizzy"))); petPeople.put(new Person("Isaac"), Arrays.asList(new Rat("Freckly"))); } public static void main(String[] args){ System.out.println("People: "+petPeople.keySet()); System.out.println("Pets: "+petPeople.values()); for(Person person: petPeople.keySet()){ System.out.println(person+"has"); for(Pet pet :petPeople.get(person)) System.out.println(" "+pet); } } }
1 import pets.*; 2 3 import java.util.*; 4 5 /** 6 * @author zlz099: 7 * @version 创建时间:2017年10月11日 上午11:12:10 8 */ 9 10 public class MapOfList { 11 public static Map<Person, List<? extends Pet>> petPeople 12 = new HashMap<Person, List<? extends Pet>>(); 13 static { 14 petPeople.put(new Person("Dawn"), Arrays.asList(new Cymric("Holly"),new Mutt("Spot"))); 15 petPeople.put(new Person("Kate"), Arrays.asList(new Cat("Shackleton"), 16 new Cat("Elsie May"),new Dog("Margrett"))); 17 petPeople.put(new Person("Marilyn"), Arrays.asList(new Pug("Louie aka Louis Snorkelstein Dupree"), 18 new Cat("Stanford aka Stinky el Negro"), 19 new Cat("Prinkola"))); 20 petPeople.put(new Person("Luke"), Arrays.asList(new Rat("Fussy"),new Rat("Fizzy"))); 21 petPeople.put(new Person("Isaac"), Arrays.asList(new Rat("Freckly"))); 22 } 23 public static void main(String[] args){ 24 System.out.println("People: "+petPeople.keySet()); 25 System.out.println("Pets: "+petPeople.values()); 26 for(Person person: petPeople.keySet()){ 27 System.out.println(person+"has"); 28 for(Pet pet :petPeople.get(person)) 29 System.out.println(" "+pet); 30 } 31 } 32 }
1 import pets.*; 2 3 import java.util.*; 4 5 /** 6 * @author zlz099: 7 * @version 创建时间:2017年10月11日 上午11:12:10 8 */ 9 10 public class MapOfList { 11 public static Map<Person, List<? extends Pet>> petPeople 12 = new HashMap<Person, List<? extends Pet>>(); 13 static { 14 petPeople.put(new Person("Dawn"), Arrays.asList(new Cymric("Holly"),new Mutt("Spot"))); 15 petPeople.put(new Person("Kate"), Arrays.asList(new Cat("Shackleton"), 16 new Cat("Elsie May"),new Dog("Margrett"))); 17 petPeople.put(new Person("Marilyn"), Arrays.asList(new Pug("Louie aka Louis Snorkelstein Dupree"), 18 new Cat("Stanford aka Stinky el Negro"), 19 new Cat("Prinkola"))); 20 petPeople.put(new Person("Luke"), Arrays.asList(new Rat("Fussy"),new Rat("Fizzy"))); 21 petPeople.put(new Person("Isaac"), Arrays.asList(new Rat("Freckly"))); 22 } 23 public static void main(String[] args){ 24 System.out.println("People: "+petPeople.keySet()); 25 System.out.println("Pets: "+petPeople.values()); 26 for(Person person: petPeople.keySet()){ 27 System.out.println(person+"has"); 28 for(Pet pet :petPeople.get(person)) 29 System.out.println(" "+pet); 30 } 31 } 32 }
1 import java.util.ArrayList; 2 import java.util.Arrays; 3 import java.util.Random; 4 import java.util.*; 5 6 /** 7 * @author zlz099: 8 * @version 创建时间:2017年10月12日 下午9:55:13 9 */ 10 public class ModifyingArraysAsList { 11 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 Random rand = new Random(47); 15 Integer[] ia = {1,2,3,4,5,6,7,8,9,10}; 16 List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); 17 System.out.println("Before shuffling: "+list1); 18 Collections.shuffle(list1,rand); 19 System.out.println("After shuffling: "+list1); 20 System.out.println("array: "+Arrays.toString(ia)); 21 22 List<Integer> list2 = Arrays.asList(ia); 23 System.out.println("Before shuffling: "+list2); 24 Collections.shuffle(list2,rand); 25 System.out.println("After shuffling: "+list2); 26 System.out.println("array: "+ Arrays.toString(ia)); 27 } 28 29 }
1 import java.util.*; 2 3 /** 4 * @author zlz099: 5 * @version 创建时间:2017年10月12日 下午9:30:02 6 */ 7 public class MultiIterableClass extends IterableClass{ 8 public Iterable<String> reversed(){ 9 return new Iterable<String>(){ 10 public Iterator<String> iterator() { 11 return new Iterator<String>() { 12 int current = words.length -1; 13 public boolean hasNext(){return current > -1;} 14 public String next(){return words[current--];} 15 public void remove(){throw new UnsupportedOperationException();} 16 }; 17 } 18 }; 19 } 20 public Iterable<String> randomized(){ 21 return new Iterable<String>() { 22 23 @Override 24 public Iterator<String> iterator() { 25 // TODO Auto-generated method stub 26 List<String> shuffled = new ArrayList<String>(Arrays.asList(words)); 27 Collections.shuffle(shuffled,new Random(47)); 28 return shuffled.iterator(); 29 } 30 }; 31 } 32 public static void main(String[] args) { 33 // TODO Auto-generated method stub 34 MultiIterableClass mic = new MultiIterableClass(); 35 for(String s : mic.reversed()) 36 System.out.print(s+" "); 37 System.out.println(); 38 for(String s : mic.randomized()) 39 System.out.print(s+" "); 40 System.out.println(); 41 for(String s : mic) 42 System.out.print(s); 43 System.out.println(); 44 } 45 46 }
1 import java.util.Iterator; 2 3 import org.omg.CORBA.NVList; 4 5 import pets.*; 6 7 /** 8 * @author zlz099: 9 * @version 创建时间:2017年10月11日 下午4:29:03 10 */ 11 class PetSequence{ 12 protected Pet[] pets = Pets.createArray(8); 13 } 14 public class NonCollectionSequence extends PetSequence{ 15 public Iterator<Pet> iterator(){ 16 return new Iterator<Pet>() { 17 private int index = 0; 18 public boolean hasNext(){ 19 return index < pets.length; 20 } 21 public Pet next(){return pets[index++];} 22 public void remove(){throw new UnsupportedOperationException();} 23 }; 24 } 25 public static void main(String[] args) { 26 // TODO Auto-generated method stub 27 NonCollectionSequence nc = new NonCollectionSequence(); 28 InterfaceVsIterator.display(nc.iterator()); 29 } 30 }
1 import java.util.HashMap; 2 import java.util.Map; 3 4 import pets.*; 5 6 /** 7 * @author zlz099: 8 * @version 创建时间:2017年10月11日 上午11:04:05 9 */ 10 public class PetMap { 11 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 Map<String,Pet> petMap = new HashMap<String, Pet>(); 15 petMap.put("My Cat", new Cat("Molly")); 16 petMap.put("My Dog", new Dog("Ginger")); 17 petMap.put("My Hamster", new Hamster("Bosco")); 18 System.out.println(petMap); 19 Pet dog = petMap.get("My Dog"); 20 System.out.println(dog); 21 System.out.println(petMap.containsKey("My Dog")); 22 System.out.println(petMap.containsValue(dog)); 23 24 } 25 26 }
1 import java.util.HashMap; 2 import java.util.Map; 3 4 import pets.*; 5 6 /** 7 * @author zlz099: 8 * @version 创建时间:2017年10月11日 上午11:04:05 9 */ 10 public class PetMap { 11 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 Map<String,Pet> petMap = new HashMap<String, Pet>(); 15 petMap.put("My Cat", new Cat("Molly")); 16 petMap.put("My Dog", new Dog("Ginger")); 17 petMap.put("My Hamster", new Hamster("Bosco")); 18 System.out.println(petMap); 19 Pet dog = petMap.get("My Dog"); 20 System.out.println(dog); 21 System.out.println(petMap.containsKey("My Dog")); 22 System.out.println(petMap.containsValue(dog)); 23 24 } 25 26 }
import java.util.*; /** * @author zlz099: * @version 创建时间:2017年9月28日 上午11:10:56 */ public class PrintContainers { 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) { // TODO Auto-generated method stub 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>())); } }
import java.util.*; /** * @author zlz099: * @version 创建时间:2017年9月28日 上午11:10:56 */ public class PrintContainers { 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) { // TODO Auto-generated method stub 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>())); } }
1 import java.util.ArrayList; 2 import java.util.Arrays; 3 import java.util.Collections; 4 import java.util.HashSet; 5 import java.util.List; 6 import java.util.PriorityQueue; 7 import java.util.Random; 8 import java.util.Set; 9 10 /** 11 * @author zlz099: 12 * @version 创建时间:2017年10月11日 下午3:17:29 13 */ 14 public class PriorityQueueDemo { 15 16 public static void main(String[] args) { 17 // TODO Auto-generated method stub 18 PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>(); 19 Random rand = new Random(47); 20 for(int i = 0; i < 10; i++) 21 priorityQueue.offer(rand.nextInt(i+10)); 22 QueueDemo.printQ(priorityQueue); 23 List<Integer> ints = Arrays.asList(25,22,20,18,14,9,3,1,1,2,3,9,14,18,21,23,25); 24 priorityQueue = new PriorityQueue<Integer>(ints); 25 QueueDemo.printQ(priorityQueue); 26 priorityQueue = new PriorityQueue<Integer>(ints.size(),Collections.reverseOrder()); 27 priorityQueue.addAll(ints); 28 QueueDemo.printQ(priorityQueue); 29 30 String fact = "EDUCATION SHOULD ESCHEW OBFUSCATION"; 31 List<String> strings = Arrays.asList(fact.split("")); 32 PriorityQueue<String> stringPQ = new PriorityQueue<String>(strings); 33 QueueDemo.printQ(stringPQ); 34 stringPQ = new PriorityQueue<String>(strings.size(),Collections.reverseOrder()); 35 stringPQ.addAll(strings); 36 QueueDemo.printQ(stringPQ); 37 38 Set<Character> charSet = new HashSet<Character>(); 39 for(char c : fact.toCharArray()) 40 charSet.add(c); 41 PriorityQueue<Character> characterPQ = new PriorityQueue<Character>(charSet); 42 QueueDemo.printQ(characterPQ); 43 } 44 45 }
1 import java.util.LinkedList; 2 import java.util.Queue; 3 import java.util.Random; 4 5 /** 6 * @author zlz099: 7 * @version 创建时间:2017年10月11日 下午3:03:28 8 */ 9 public class QueueDemo { 10 public static void printQ(Queue queue){ 11 while(queue.peek()!=null) 12 System.out.print(queue.remove()+" "); 13 System.out.println(); 14 } 15 public static void main(String[] args) { 16 // TODO Auto-generated method stub 17 Queue<Integer> queue = new LinkedList<Integer>(); 18 Random rand = new Random(47); 19 for(int i = 0; i < 10;i++) 20 queue.offer(rand.nextInt(i+10)); 21 printQ(queue); 22 Queue<Character> qc = new LinkedList<Character>(); 23 for(char c :"Brontosaurus".toCharArray()) 24 qc.offer(c); 25 printQ(qc); 26 } 27 28 }
1 import java.util.LinkedList; 2 import java.util.Queue; 3 import java.util.Random; 4 5 /** 6 * @author zlz099: 7 * @version 创建时间:2017年10月11日 下午3:03:28 8 */ 9 public class QueueDemo { 10 public static void printQ(Queue queue){ 11 while(queue.peek()!=null) 12 System.out.print(queue.remove()+" "); 13 System.out.println(); 14 } 15 public static void main(String[] args) { 16 // TODO Auto-generated method stub 17 Queue<Integer> queue = new LinkedList<Integer>(); 18 Random rand = new Random(47); 19 for(int i = 0; i < 10;i++) 20 queue.offer(rand.nextInt(i+10)); 21 printQ(queue); 22 Queue<Character> qc = new LinkedList<Character>(); 23 for(char c :"Brontosaurus".toCharArray()) 24 qc.offer(c); 25 printQ(qc); 26 } 27 28 }
1 import java.util.*; 2 3 /** 4 * @author zlz099: 5 * @version 创建时间:2017年10月11日 上午10:01:20 6 */ 7 public class SetOfInteger { 8 9 public static void main(String[] args) { 10 // TODO Auto-generated method stub 11 Random rand = new Random(47); 12 Set<Integer> intset = new HashSet<Integer>(); 13 for(int i = 0 ;i < 10000;i++) 14 intset.add(rand.nextInt(10)); 15 System.out.println(intset); 16 } 17 18 }
1 /** 2 * @author zlz099: 3 * @version 创建时间:2017年10月11日 上午10:32:51 4 */ 5 import java.util.*; 6 public class SetOperation { 7 8 public static void main(String[] args) { 9 // TODO Auto-generated method stub 10 Set<String> set1 = new HashSet<String>(); 11 Collections.addAll(set1, "A B C D E F G H I J K L".split(" ")); 12 set1.add("M"); 13 System.out.println("H: "+set1.contains("H")); 14 System.out.println("N: "+set1.contains("N")); 15 Set<String> set2 = new HashSet<String>(); 16 Collections.addAll(set2, "H I J K L".split(" ")); 17 System.out.println("set2 in set1: "+set1.containsAll(set2)); 18 set1.remove("H"); 19 System.out.println("Set1: "+set1); 20 System.out.println("set2 in set1: "+set1.containsAll(set2)); 21 set1.removeAll(set2); 22 System.out.println("set2 removed from set1: "+set1); 23 Collections.addAll(set1, "X Y Z".split(" ")); 24 System.out.println(" ‘X Y Z‘ added to set1: "+set1); 25 } 26 }
1 import java.util.ArrayList; 2 import java.util.Collection; 3 4 /** 5 * @author zlz099: 6 * @version 创建时间:2017年9月28日 上午10:28:20 7 */ 8 public class SimpleCollection { 9 10 public static void main(String[] args) { 11 // TODO Auto-generated method stub 12 Collection<Integer> c = new ArrayList<Integer>(); 13 for(int i = 0; i < 10; i++) 14 c.add(i); 15 for(Integer i : c) 16 System.out.print(i+", "); 17 18 } 19 20 }
1 /** 2 * @author zlz099: 3 * @version 创建时间:2017年10月9日 上午11:14:58 4 */ 5 import java.util.Iterator; 6 import java.util.List; 7 8 import pets.*; 9 10 public class SimpleIteration { 11 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 List<Pet> pets = Pets.arrayList(12); 15 Iterator<Pet> it = pets.iterator(); 16 while(it.hasNext()){ 17 Pet p = it.next(); 18 System.out.print(p.id()+":"+p+" "); 19 } 20 System.out.println(); 21 for(Pet p : pets){ 22 System.out.print(p.id()+":"+p+" "); 23 } 24 System.out.println(); 25 it = pets.iterator(); 26 for(int i = 0; i<6;i++){ 27 it.next(); 28 it.remove(); 29 } 30 System.out.print(pets); 31 32 } 33 34 35 }
1 import java.util.Random; 2 import java.util.SortedSet; 3 import java.util.TreeSet; 4 5 /** 6 * @author zlz099: 7 * @version 创建时间:2017年10月11日 上午10:27:46 8 */ 9 public class SortedSetOfInteger { 10 11 public static void main(String[] args) { 12 // TODO Auto-generated method stub 13 Random rand = new Random(47); 14 SortedSet<Integer> intset = new TreeSet<Integer>(); 15 for(int i = 0; i < 1000 ; i++) 16 intset.add(rand.nextInt(30)); 17 System.out.println(intset); 18 } 19 20 }
1 import java.util.HashMap; 2 import java.util.Map; 3 import java.util.Random; 4 5 /** 6 * @author zlz099: 7 * @version 创建时间:2017年10月11日 上午10:59:46 8 */ 9 public class Statistics { 10 11 public static void main(String[] args) { 12 // TODO Auto-generated method stub 13 Random rand = new Random(47); 14 Map<Integer, Integer> m = new HashMap<Integer,Integer>(); 15 for(int i = 0; i < 10000;i++){ 16 int r = rand.nextInt(20); 17 Integer freq = m.get(r); 18 m.put(r, freq == null ? 1 : freq+1); 19 } 20 System.out.println(m); 21 } 22 }
1 package stacktest; 2 3 import java.util.LinkedList; 4 5 /** 6 * @author zlz099: 7 * @version 创建时间:2017年10月9日 下午9:59:42 8 */ 9 public class Stack<T> { 10 private LinkedList<T> storage = new LinkedList<T>(); 11 public void push(T v){storage.addFirst(v);} 12 public T peek(){return storage.getFirst();} 13 public T pop(){return storage.removeFirst();} 14 public boolean empty(){return storage.isEmpty();} 15 public String toString(){return storage.toString();} 16 }
1 package stacktest; 2 /** 3 * @author zlz099: 4 * @version 创建时间:2017年10月11日 上午9:45:44 5 */ 6 public class StackCollection { 7 8 public static void main(String[] args) { 9 // TODO Auto-generated method stub 10 stacktest.Stack<String> stack = new stacktest.Stack<String>(); 11 for(String s : "My dog has fleas".split(" ")) 12 stack.push(s); 13 while(!stack.empty()) 14 System.out.print(stack.pop()+" "); 15 System.out.println(); 16 java.util.Stack<String> stack2 = new java.util.Stack<String>(); 17 for(String s :"My dog has fleas".split(" ")) 18 stack2.push(s); 19 while(!stack2.empty()) 20 System.out.print(stack2.pop()+" "); 21 } 22 23 }
1 package stacktest; 2 /** 3 * @author zlz099: 4 * @version 创建时间:2017年10月9日 下午10:05:42 5 */ 6 public class StackTest { 7 8 public static void main(String[] args) { 9 // TODO Auto-generated method stub 10 Stack<String> stack = new Stack<String>(); 11 for(String s : "My dogs has fleas".split(" ")) 12 stack.push(s); 13 while(!stack.empty()) 14 System.out.print(stack.pop()+" "); 15 } 16 }
以上是关于《Java编程思想》第十一章 持有对象的主要内容,如果未能解决你的问题,请参考以下文章