From e9b0698f2a7f27adc1fa4464276d14a51f4025ea Mon Sep 17 00:00:00 2001 From: btp <842297171@qq.com> Date: Sat, 27 May 2017 15:35:50 +0800 Subject: [PATCH 1/7] 170537-Generic --- src/btp/oneP/GenericErase.java | 22 ++++++++++++++++++++++ src/btp/oneP/GenericEvaluate.java | 29 +++++++++++++++++++++++++++++ src/btp/oneP/ListCopy.java | 24 ++++++++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 src/btp/oneP/GenericErase.java create mode 100644 src/btp/oneP/GenericEvaluate.java create mode 100644 src/btp/oneP/ListCopy.java diff --git a/src/btp/oneP/GenericErase.java b/src/btp/oneP/GenericErase.java new file mode 100644 index 0000000..ac37850 --- /dev/null +++ b/src/btp/oneP/GenericErase.java @@ -0,0 +1,22 @@ +package btp.oneP; + +import java.lang.reflect.Method; +import java.util.ArrayList; + +public class GenericErase { + + public static void main(String[] args) { + ArrayList sl = new ArrayList(); + sl.add("Magic"); + Class clazz = sl.getClass(); + try{ + Method method = clazz.getMethod("add", Object.class); + method.invoke(sl, 1); + System.out.println(sl); + //out:[Magic, 1] + }catch(Exception e){ + e.printStackTrace(); + } + } + +} diff --git a/src/btp/oneP/GenericEvaluate.java b/src/btp/oneP/GenericEvaluate.java new file mode 100644 index 0000000..caa27e1 --- /dev/null +++ b/src/btp/oneP/GenericEvaluate.java @@ -0,0 +1,29 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Collection; + +public class GenericEvaluate { + + public static void main(String[] args) { + Collection> c1 = new ArrayList>(); + Collection> c2 = c1; + //Collection> c3 = c1; + Collection> c4 = c1; + + Collection> c5 = new ArrayList>(); + //Collection> c6 = c5; + Collection> c7 = c5; + //Collection> c8 = c5; + Collection> c9 = c5; + } + +} + +class Pair{ + +} + +class SubTypeOfPair extends Pair{ + +} diff --git a/src/btp/oneP/ListCopy.java b/src/btp/oneP/ListCopy.java new file mode 100644 index 0000000..9c4cae4 --- /dev/null +++ b/src/btp/oneP/ListCopy.java @@ -0,0 +1,24 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class ListCopy { + + public static void copy(List src,List dest){ + for(T t:src){ + dest.add(t); + } + } + + public static void main(String[] args) { + List sList = new ArrayList(Arrays.asList(new String[]{"hehe","xixi","caca"})); + List oList = new ArrayList(); + copy(sList,oList); + for(Object o:oList){ + System.out.println(o); + } + } + +} From effccdb633d3703548e70935377919202105fe20 Mon Sep 17 00:00:00 2001 From: btp <842297171@qq.com> Date: Sun, 28 May 2017 16:15:08 +0800 Subject: [PATCH 2/7] 0528-Generic --- src/btp/oneP/Byteset.java | 14 ++++ src/btp/oneP/CRGWithBasicHolder.java | 27 ++++++++ src/btp/oneP/CaptureConversion.java | 24 +++++++ src/btp/oneP/CheckedList.java | 39 +++++++++++ src/btp/oneP/ClassCasting.java | 26 +++++++ src/btp/oneP/ComparablePet.java | 30 +++++++++ src/btp/oneP/Covarance.java | 90 +++++++++++++++++++++++++ src/btp/oneP/Employee.java | 33 +++++++++ src/btp/oneP/GenericExceptionTest.java | 11 +++ src/btp/oneP/SelfBounded.java | 52 ++++++++++++++ src/btp/oneP/ThrowGenericException.java | 83 +++++++++++++++++++++++ src/btp/oneP/Wildcards.java | 15 +++++ 12 files changed, 444 insertions(+) create mode 100644 src/btp/oneP/Byteset.java create mode 100644 src/btp/oneP/CRGWithBasicHolder.java create mode 100644 src/btp/oneP/CaptureConversion.java create mode 100644 src/btp/oneP/CheckedList.java create mode 100644 src/btp/oneP/ClassCasting.java create mode 100644 src/btp/oneP/ComparablePet.java create mode 100644 src/btp/oneP/Covarance.java create mode 100644 src/btp/oneP/Employee.java create mode 100644 src/btp/oneP/GenericExceptionTest.java create mode 100644 src/btp/oneP/SelfBounded.java create mode 100644 src/btp/oneP/ThrowGenericException.java diff --git a/src/btp/oneP/Byteset.java b/src/btp/oneP/Byteset.java new file mode 100644 index 0000000..35a79c7 --- /dev/null +++ b/src/btp/oneP/Byteset.java @@ -0,0 +1,14 @@ +package btp.oneP; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class Byteset { + Byte[] possibles = {1,2,3,4,5,6,7,8,9}; + Set myset = new HashSet(Arrays.asList(possibles)); + + Set myset2 = new HashSet(Arrays.asList(new Byte[]{1,2,3,4,5,6,7,8,9})); + //The parameterized method asList(Byte...) of type Arrays is not applicable for the arguments (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) + //Set myset3 = new HashSet(Arrays.asList(1,2,3,4,5,6,7,8,9)); +} diff --git a/src/btp/oneP/CRGWithBasicHolder.java b/src/btp/oneP/CRGWithBasicHolder.java new file mode 100644 index 0000000..d20f854 --- /dev/null +++ b/src/btp/oneP/CRGWithBasicHolder.java @@ -0,0 +1,27 @@ +package btp.oneP; + +public class CRGWithBasicHolder { + + public static void main(String[] args) { + Subtype st1 = new Subtype(),st2 = new Subtype(); + st1.set(st2); + Subtype st3 = st1.get(); + st1.f(); + } + +} + +class BasicHolder{ + T element; + void set(T t){ + element = t; + } + T get(){ + return this.element; + } + void f(){ + System.out.println(this.element.getClass().getName()); + } +} + +class Subtype extends BasicHolder{} \ No newline at end of file diff --git a/src/btp/oneP/CaptureConversion.java b/src/btp/oneP/CaptureConversion.java new file mode 100644 index 0000000..964ae23 --- /dev/null +++ b/src/btp/oneP/CaptureConversion.java @@ -0,0 +1,24 @@ +package btp.oneP; + +public class CaptureConversion { + + static void f1(Holder holder){ + T t = holder.get(); + System.out.println(t.getClass().getSimpleName()); + } + + static void f2(Holder holder){ + f1(holder); + } + public static void main(String[] args) { + Holder raw = new Holder(1); + f1(raw); + f2(raw); + Holder rawBasic = new Holder(); + rawBasic.set(new Object()); + f2(rawBasic); + Holder wildcarded = new Holder(1.0); + f2(wildcarded); + } + +} diff --git a/src/btp/oneP/CheckedList.java b/src/btp/oneP/CheckedList.java new file mode 100644 index 0000000..cf99872 --- /dev/null +++ b/src/btp/oneP/CheckedList.java @@ -0,0 +1,39 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class CheckedList { + + @SuppressWarnings("unchecked") + static void oldStyleMethod(List probablyDogs){ + probablyDogs.add(new Cat()); + } + + public static void main(String[] args) { + List dogs1 = new ArrayList(); + oldStyleMethod(dogs1); + System.out.println(dogs1); + Lists2 = Collections.checkedList(new ArrayList(), Dog.class); + try{ + oldStyleMethod(s2); + }catch(Exception e){ + e.printStackTrace(); + } + + //work fine + List pets = Collections.checkedList(new ArrayList(), Pet.class); + pets.add(new Dog()); + pets.add(new Cat()); + pets.add(new Pet()); + oldStyleMethod(pets); + System.out.println(pets); + } + +} + +class Pet{} +class Dog extends Pet{} +class Cat extends Pet{} + diff --git a/src/btp/oneP/ClassCasting.java b/src/btp/oneP/ClassCasting.java new file mode 100644 index 0000000..b80fa8c --- /dev/null +++ b/src/btp/oneP/ClassCasting.java @@ -0,0 +1,26 @@ +package btp.oneP; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.util.List; + +public class ClassCasting { + + public void f(String...args) throws FileNotFoundException, IOException, ClassNotFoundException{ + ObjectInputStream in = new ObjectInputStream( + new FileInputStream(args[0])); + //List lwl = List.class.ClassCasting(in.readObject()); + //List lw2 = (List)List.class.cast(in.readObject()); + List lw2 = List.class.cast(in.readObject()); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} + +class Widget{} diff --git a/src/btp/oneP/ComparablePet.java b/src/btp/oneP/ComparablePet.java new file mode 100644 index 0000000..ba87d94 --- /dev/null +++ b/src/btp/oneP/ComparablePet.java @@ -0,0 +1,30 @@ +package btp.oneP; + +public class ComparablePet implements Comparable { + + @Override + public int compareTo(ComparablePet o) { + return 0; + } + +} + +//以下是错误的,等于同时两个泛型参数 +//class Cat extends ComparablePet implements Comparable{} + + +class Hamster extends ComparablePet implements Comparable{ + //其实这就等于重写,子类Hamster重写了父类ComparablePet的方法 + @Override + public int compareTo(ComparablePet o) { + return 0; + } +} + +//Gecko和Hanster的效果一样 +class Gecko extends ComparablePet{ + @Override + public int compareTo(ComparablePet o) { + return 0; + } +} \ No newline at end of file diff --git a/src/btp/oneP/Covarance.java b/src/btp/oneP/Covarance.java new file mode 100644 index 0000000..9fecfcf --- /dev/null +++ b/src/btp/oneP/Covarance.java @@ -0,0 +1,90 @@ +package btp.oneP; + +public class Covarance { + + public static void main(String[] args) { + // TODO Auto-generated method stub + BaseX bx = new BaseX(); + DerivedX dx = new DerivedX(); + DerivedSetter d = new DerivedSetter(); + d.set(dx); + d.set(bx); + //---------------- + DerivedGS dgs = new DerivedGS(); + dgs.set(bx); + dgs.set(dx); + + } + +} + +class BaseX{} +class DerivedX extends BaseX{} + +interface OrdinaryGetter{ + BaseX get(); +} + +interface DerivedGetter extends OrdinaryGetter{ + DerivedX get(); +} + +class CovariantReturnTypes{ + void test(DerivedGetter d){ + DerivedX d2 = d.get(); + } +} + +interface GenericGetter>{ + T get(); +} + +interface Getter extends GenericGetter{ + +} + +class GenericsAndReturnTypes{ + void test(Getter g){ + Getter result = g.get(); + GenericGetter gg = g.get(); + } +} + + +class OrdinarySetter{ + void set(BaseX base){ + System.out.println("OrdinarySetter.set(BaseX)"); + } +} + +class DerivedSetter extends OrdinarySetter{ + //这不是重写,这是重载 + void set(DerivedX derived){ + System.out.println("DerivedSetter.set(Derived)"); + } +} + +interface SelfBoundSetter>{ + void set(T arg); +} + +interface GSetter extends SelfBoundSetter{} + +class SelfBoundingAndCovariantArgument{ + void testA(GSetter s1,GSetter s2,SelfBoundSetter sbs){ + s1.set(s2); + //s1.set(sbs); + } +} + +class GenericSetter{ + void set(T t){ + System.out.println("GenericSetter.set(Base)"); + } +} + +class DerivedGS extends GenericSetter{ + void set(DerivedX derivedx){ + System.out.println("DerivedGS.set(Derived)"); + } +} \ No newline at end of file diff --git a/src/btp/oneP/Employee.java b/src/btp/oneP/Employee.java new file mode 100644 index 0000000..0a98de3 --- /dev/null +++ b/src/btp/oneP/Employee.java @@ -0,0 +1,33 @@ +package btp.oneP; + +public class Employee implements Payable{ + + @Override + public void getPay() { + // TODO Auto-generated method stub + + } + +} + + +interface Payable{ + void getPay(); +} + +class Hourly extends Employee implements Payable{} + + + +/*public class Employee implements Payable{ + + @Override + public void getPay() { + // TODO Auto-generated method stub + + } + +} + + +class Hourly extends Employee implements Payable{}*/ \ No newline at end of file diff --git a/src/btp/oneP/GenericExceptionTest.java b/src/btp/oneP/GenericExceptionTest.java new file mode 100644 index 0000000..e26e6cf --- /dev/null +++ b/src/btp/oneP/GenericExceptionTest.java @@ -0,0 +1,11 @@ +package btp.oneP; +//The generic class GenericExceptionTest may not subclass java.lang.Throwable +//public class GenericExceptionTest extends Exception X +public class GenericExceptionTest{ + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/src/btp/oneP/SelfBounded.java b/src/btp/oneP/SelfBounded.java new file mode 100644 index 0000000..2c23aff --- /dev/null +++ b/src/btp/oneP/SelfBounded.java @@ -0,0 +1,52 @@ +package btp.oneP; + +//泛型归根到底就是一种限定 +public class SelfBounded>{ + T element; + SelfBounded set(T t){ + this.element = t; + return this; + } + T get(){ + return this.element; + } + + public static void main(String[] args) { + AS as = new AS(); + as.set(new AS()); + as=as.set(new AS()).get(); + as = as.get(); + CS cs = new CS(); + cs = cs.set(new CS()).get(); + + BS bs = new BS(); + bs.set(new AS()); + as = bs.get(); + as = bs.set(new AS()).get(); + } + +} +/* + * T为AS + * AS继承自SelfBounded + */ +class AS extends SelfBounded{} + +/* + * T为BS + * BS继承自SelfBounded + */ +class BS extends SelfBounded{} + +class CS extends SelfBounded{} + +class D{} +/* + * D不是集成自SelfBounded,所以出错 + */ +//class E extends SelfBounded{} +/* + * SelfBounded渴望一个类型参数,但是没有,所以会出警告 + */ +class F extends SelfBounded{} + diff --git a/src/btp/oneP/ThrowGenericException.java b/src/btp/oneP/ThrowGenericException.java new file mode 100644 index 0000000..295bcea --- /dev/null +++ b/src/btp/oneP/ThrowGenericException.java @@ -0,0 +1,83 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.List; + +public class ThrowGenericException { + + public static void main(String[] args) { + ProcessRunner runner = new ProcessRunner(); + for(int i=0;i<3;i++){ + runner.add(new Processor1()); + } + try{ + System.out.println(runner.processAll()); + }catch(Failure1 e){ + e.printStackTrace(); + } + + ProcessRunner runner2 = new ProcessRunner(); + for(int i=0;i<3;i++){ + runner2.add(new Processor2()); + } + + try{ + System.out.println(runner2.processAll()); + }catch(Failure2 e){ + e.printStackTrace(); + } + } + +} + +interface Processor{ + void process(List resultCollector) throws E; +} + +class ProcessRunner + extends ArrayList>{ + List processAll() throws E{ + List resultCollector = new ArrayList(); + for(Processor p:this){ + p.process(resultCollector); + } + return resultCollector; + } +} + +class Failure1 extends Exception{} + +class Processor1 implements Processor{ + static int count = 3; + @Override + public void process(List resultCollector) throws Failure1 { + if(count-- > 1){ + resultCollector.add("Hep!"); + }else{ + resultCollector.add("Ho!"); + } + if(count < 0){ + throw new Failure1(); + } + } + +} + + +class Failure2 extends Exception{} + +class Processor2 implements Processor{ + static int count = 3; + @Override + public void process(List resultCollector) throws Failure2 { + if(count-- == 0){ + resultCollector.add(47); + }else{ + resultCollector.add(11); + } + if(count < 0){ + throw new Failure2(); + } + } + +} diff --git a/src/btp/oneP/Wildcards.java b/src/btp/oneP/Wildcards.java index 6dbdec3..4a5cec9 100644 --- a/src/btp/oneP/Wildcards.java +++ b/src/btp/oneP/Wildcards.java @@ -62,6 +62,21 @@ public static void main(String[] args) { System.out.println(r3); Long r4 = exact1(bounded); System.out.println(r4); + + Long r5 = exact2(raw,lng); + Long r6 = exact2(qualified,lng); + //Long r7 = exact2(unbounded,lng); + //Long r8 = exact2(bounded,lng); + + Long r9 = wildSubtype(raw,lng); + Long r10 = wildSubtype(qualified,lng); + Object r11 = wildSubtype(unbounded,lng); + Long r12 = wildSubtype(bounded,lng); + + wildSupertype(raw,lng); + wildSupertype(qualified,lng); + //wildSupertype(unbounded,lng); + //wildSupertype(bounded,lng); } } From 8ab3b67c4672db1ee14a1d3cc768280f608ef7a8 Mon Sep 17 00:00:00 2001 From: btp <842297171@qq.com> Date: Tue, 30 May 2017 23:33:31 +0800 Subject: [PATCH 3/7] Chapter-15-Generic-btp0530 --- src/btp/oneP/ApplyTest.java | 93 ++++++++++++++ src/btp/oneP/Decoration.java | 67 ++++++++++ src/btp/oneP/DecoratorTest.java | 163 ++++++++++++++++++++++++ src/btp/oneP/DogsAndRobots.java | 61 +++++++++ src/btp/oneP/DynamicProxyMixin.java | 58 +++++++++ src/btp/oneP/Fill2Test.java | 57 +++++++++ src/btp/oneP/FillTest.java | 45 +++++++ src/btp/oneP/Functional.java | 187 ++++++++++++++++++++++++++++ src/btp/oneP/LatentReflection.java | 58 +++++++++ 9 files changed, 789 insertions(+) create mode 100644 src/btp/oneP/ApplyTest.java create mode 100644 src/btp/oneP/Decoration.java create mode 100644 src/btp/oneP/DecoratorTest.java create mode 100644 src/btp/oneP/DogsAndRobots.java create mode 100644 src/btp/oneP/DynamicProxyMixin.java create mode 100644 src/btp/oneP/Fill2Test.java create mode 100644 src/btp/oneP/FillTest.java create mode 100644 src/btp/oneP/Functional.java create mode 100644 src/btp/oneP/LatentReflection.java diff --git a/src/btp/oneP/ApplyTest.java b/src/btp/oneP/ApplyTest.java new file mode 100644 index 0000000..08e3eef --- /dev/null +++ b/src/btp/oneP/ApplyTest.java @@ -0,0 +1,93 @@ +package btp.oneP; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +public class ApplyTest { + + public static void main(String[] args) throws NoSuchMethodException, SecurityException { + List shapes = new ArrayList(); + for(int i=0;i<10;i++){ + shapes.add(new Shape()); + } + Apply.apply(shapes, Shape.class.getMethod("rotate")); + + Apply.apply(shapes, Shape.class.getMethod("resize", int.class), 5); + + + List squares = new ArrayList(); + for(int i=0;i<10;i++){ + squares.add(new Square()); + } + Apply.apply(squares, Square.class.getMethod("rotate")); + + Apply.apply(squares, Square.class.getMethod("resize", int.class), 5); + + + Apply.apply(new FilledList(Shape.class,5), Shape.class.getMethod("rotate")); + Apply.apply(new FilledList(Square.class,18), Shape.class.getMethod("resize", int.class),15); + + SimpleQueue shapeQ = new SimpleQueue(); + for(int i=0;i<5;i++){ + shapeQ.add(new Shape()); + shapeQ.add(new Square()); + } + Apply.apply(shapeQ, Shape.class.getMethod("rotate")); + } + +} + +class Apply{ + public static > void apply(S seq,Method f,Object...args){ + try{ + for(T t:seq){ + f.invoke(t, args); + } + }catch(Exception e){ + throw new RuntimeException(); + } + } +} + +class Shape{ + public void rotate(){ + System.out.println(this+" rotate"); + } + public void resize(int newSize){ + System.out.println(this+" resize"+newSize); + } +} + +class Square extends Shape{} + +class FilledList extends ArrayList{ + public FilledList(Class type,int size){ + try{ + for(int i = 0;i implements Iterable{ + private LinkedList storage = new LinkedList(); + public void add(T t){ + this.storage.offer(t); + } + public T get(){ + return this.storage.poll(); + } + @Override + public Iterator iterator() { + return this.storage.iterator(); + } + +} + + diff --git a/src/btp/oneP/Decoration.java b/src/btp/oneP/Decoration.java new file mode 100644 index 0000000..65f7b3c --- /dev/null +++ b/src/btp/oneP/Decoration.java @@ -0,0 +1,67 @@ +package btp.oneP; + +import java.util.Date; + +public class Decoration { + + public static void main(String[] args) { + TimeStamped t = new TimeStamped(new Basic()); + TimeStamped t2 = new TimeStamped(new SerialNumbered(new Basic())); + //t2.getSerialNumber();//Not available + System.out.println(t2.getStamp()); + SerialNumbered s = new SerialNumbered(new Basic()); + SerialNumbered s2 = new SerialNumbered(new TimeStamped(new Basic())); + SerialNumbered s3 = new SerialNumbered(new TimeStamped(new Basic())); + System.out.println(s.getSerialNumber()); + System.out.println(s2.getSerialNumber()); + System.out.println(s3.getSerialNumber()); + //s2.getStamp();//Not available + } + +} + + +class Basic{ + private String value; + public void set(String value){ + this.value = value; + } + public String get(){ + return value; + } +} + +class Decorator extends Basic{ + protected Basic basic; + public Decorator(Basic basic){ + this.basic = basic; + } + public void set(String val){ + basic.set(val); + } + public String get(){ + return basic.get(); + } +} + +class TimeStamped extends Decorator{ + private final long timeStamp; + public TimeStamped(Basic basic) { + super(basic); + timeStamp = new Date().getTime(); + } + public long getStamp(){ + return timeStamp; + } +} + +class SerialNumbered extends Decorator{ + private static long counter = 1; + private final long serialNumber = counter++; + public SerialNumbered(Basic basic) { + super(basic); + } + public long getSerialNumber(){ + return serialNumber; + } +} \ No newline at end of file diff --git a/src/btp/oneP/DecoratorTest.java b/src/btp/oneP/DecoratorTest.java new file mode 100644 index 0000000..6efc792 --- /dev/null +++ b/src/btp/oneP/DecoratorTest.java @@ -0,0 +1,163 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.List; + +public class DecoratorTest { + + @SuppressWarnings("static-access") + public static void main(String[] args) { + OriginalCoffee originalCoffee = new OriginalCoffee(); + double priceMilk = 10.0; + Milk milkCoffee = new Milk(originalCoffee,priceMilk); + milkCoffee.mixing(); + System.out.println("当前咖啡中的配料:"+milkCoffee.foodList); + System.out.println("当前咖啡价格:"+milkCoffee.getPrice()); + System.out.println("---------------------------"); + double priceMatcha = 20.0; + Matcha matchaCoffee = new Matcha(milkCoffee,priceMatcha); + matchaCoffee.mixing(); + System.out.println("当前咖啡中的配料:"+matchaCoffee.foodList); + System.out.println("当前咖啡价格:"+matchaCoffee.getPrice()); + System.out.println("---------------------------"); + double priceChocolate = 30.0; + Chocolate chocolateCoffee = new Chocolate(matchaCoffee,priceChocolate); + chocolateCoffee.mixing(); + System.out.println("当前咖啡中的配料:"+chocolateCoffee.foodList); + System.out.println("当前咖啡价格:"+chocolateCoffee.getPrice()); + System.out.println("---------------------------"); + } + +} + +/** + * 装饰品和被装饰器的共同接口 + * + */ +interface CoffeeTaste{ + //返回价格 + double getPrice(); + //搅拌咖啡 + void mixing(); +} + +/** + * 原始的被装饰器 + * + */ +class OriginalCoffee implements CoffeeTaste{ + private String name; + public OriginalCoffee(){ + name = "原味咖啡"; + System.out.println("原味咖啡的价格是:50"); + } + @Override + public double getPrice() { + //原味咖啡的价钱 + return 50; + } + + @Override + public void mixing() { + System.out.println("--搅拌咖啡"); + } + +} + +/** + * 装饰品的共同父类 + * + */ +abstract class SnacksAndDesserts implements CoffeeTaste{ + public static List foodList= new ArrayList(); + //小食和甜品的价格 + private double additionalPrice; + //要加入小食和甜品的咖啡 + CoffeeTaste coffeeTaste; + public SnacksAndDesserts(CoffeeTaste coffeeTaste,double additionalPrice){ + this.coffeeTaste = coffeeTaste; + this.additionalPrice = additionalPrice; + } + //返回价格 + @Override + public double getPrice() { + double priceNow = coffeeTaste.getPrice()+additionalPrice; + return priceNow; + } + + abstract void add(); +} + +/** + * 牛奶类 + * + */ +class Milk extends SnacksAndDesserts{ + + public Milk(CoffeeTaste coffeeTaste, double additionalPrice) { + super(coffeeTaste, additionalPrice); + System.out.println("O(∩_∩)O~~牛奶的价格是:"+additionalPrice); + } + + @Override + void add() { + System.out.println("--咖啡中加入牛奶"); + SnacksAndDesserts.foodList.add("牛奶"); + } + + @Override + public void mixing() { + add(); + System.out.println("--牛奶加入咖啡中搅拌"); + } + + +} + + +/** + * 抹茶类 + */ +class Matcha extends SnacksAndDesserts{ + + public Matcha(CoffeeTaste coffeeTaste, double additionalPrice) { + super(coffeeTaste, additionalPrice); + System.out.println("O(∩_∩)O~~抹茶的价格是:"+additionalPrice); + } + + @Override + void add() { + System.out.println("--咖啡中混入抹茶"); + SnacksAndDesserts.foodList.add("抹茶"); + } + + @Override + public void mixing() { + add(); + System.out.println("--抹茶加入咖啡中搅拌"); + } +} + +/** + * 巧克力类 + */ + +class Chocolate extends SnacksAndDesserts{ + + public Chocolate(CoffeeTaste coffeeTaste, double additionalPrice) { + super(coffeeTaste, additionalPrice); + System.out.println("O(∩_∩)O~~巧克力的价格是:"+additionalPrice); + } + + @Override + void add() { + System.out.println("--咖啡中加入巧克力"); + SnacksAndDesserts.foodList.add("巧克力"); + } + + @Override + public void mixing() { + add(); + System.out.println("--咖啡加入咖啡中搅拌"); + } +} diff --git a/src/btp/oneP/DogsAndRobots.java b/src/btp/oneP/DogsAndRobots.java new file mode 100644 index 0000000..ecb0865 --- /dev/null +++ b/src/btp/oneP/DogsAndRobots.java @@ -0,0 +1,61 @@ +package btp.oneP; + +public class DogsAndRobots { + + public static void main(String[] args) { + PerformingDog d = new PerformingDog(); + Robott r = new Robott(); + Communicate.perform(d); + Communicate.perform(r); + } + +} + +interface Performs{ + void speak(); + void sit(); +} + +class PerformingDog extends Dog implements Performs{ + + @Override + public void speak() { + System.out.println("Woof!"); + } + + @Override + public void sit() { + System.out.println("Sitting!"); + } + + public void reproduce(){} +} + +class Robott implements Performs{ + + @Override + public void speak() { + System.out.println("Click!"); + } + + @Override + public void sit() { + System.out.println("Clank!"); + } + + public void oilChange(){} + +} + +class Communicate{ + public static void perform(T performs){ + performs.speak(); + performs.sit(); + } + + //下面和上面的一样,不构成重载 + /*public static void perform(Performs p){ + p.speak(); + p.sit(); + }*/ +} \ No newline at end of file diff --git a/src/btp/oneP/DynamicProxyMixin.java b/src/btp/oneP/DynamicProxyMixin.java new file mode 100644 index 0000000..d8385d7 --- /dev/null +++ b/src/btp/oneP/DynamicProxyMixin.java @@ -0,0 +1,58 @@ +package btp.oneP; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.Map; + +public class DynamicProxyMixin { + + public static void main(String[] args) { + } + +} + +class MixinProxy implements InvocationHandler{ + Map delegatesByMethod; + public MixinProxy(TwoTuple>...pairs){ + this.delegatesByMethod = new HashMap(); + for(TwoTuple> pair:pairs){ + for(Method m : pair.second.getMethods()){ + String methodName = m.getName(); + if(!this.delegatesByMethod.containsKey(methodName)){ + this.delegatesByMethod.put(methodName, pair.first); + } + } + } + } + + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + String methodName = method.getName(); + Object delegate = this.delegatesByMethod.get(methodName); + return method.invoke(delegate, args); + } + + public static Object newInstance(TwoTuple...pairs){ + Class[] interfaces = new Class[pairs.length]; + for(int i=0;i{ + K first; + V second; + public TwoTuple(K k,V v){ + this.first = k; + this.second = v; + } +} diff --git a/src/btp/oneP/Fill2Test.java b/src/btp/oneP/Fill2Test.java new file mode 100644 index 0000000..9e39fe5 --- /dev/null +++ b/src/btp/oneP/Fill2Test.java @@ -0,0 +1,57 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class Fill2Test { + + public static void main(String[] args) { + List carrier = new ArrayList(); + Fill2.fill(new AddableCollectionAdapter(carrier), Contract.class, 3); + Fill2.fill(Adapter.collectionAdapter(carrier), Contract.class, 2); + System.out.println(carrier); + } + +} + +interface Addable{ + void add(T t); +} + +class Fill2{ + public static void fill(Addable addable,Class classToken,int size){ + for(int i=0;i implements Addable{ + private Collection c; + public AddableCollectionAdapter(Collection c){ + this.c = c; + } + @Override + public void add(T t) { + c.add(t); + } + +} + +class Adapter{ + public static Addable collectionAdapter(Collection c){ + return new AddableCollectionAdapter(c); + } +} + +class AddableSimpleQueue extends SimpleQueue implements Addable{ + public void add(T t){ + super.add(t); + } +} diff --git a/src/btp/oneP/FillTest.java b/src/btp/oneP/FillTest.java new file mode 100644 index 0000000..acaefe2 --- /dev/null +++ b/src/btp/oneP/FillTest.java @@ -0,0 +1,45 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class FillTest { + + public static void main(String[] args) { + List contracts = new ArrayList(); + Fill.fill(contracts, Contract.class, 3); + System.out.println(contracts); + + Fill.fill(contracts, TitleTransfer.class, 2); + System.out.println(contracts); + + SimpleQueue cq = new SimpleQueue(); + //Fill.fill(cq, Contract.class, 3); + } + +} + +class Fill{ + public static void fill(Collection collection,Class classToken,int size){ + for(int i=0;i li = Arrays.asList(1,2,3,4,5,6,7); + Integer result = reduce(li,new IntegerAdder()); + System.out.println(result); + + result = reduce(li,new IntegerSubtracter()); + System.out.println(result); + + System.out.println(fillter(li,new GreaterThan(4))); + + System.out.println(forEach(li,new MultiplyingIntegerCollector()).result()); + + System.out.println(forEach(fillter(li,new GreaterThan(4)), + new MultiplyingIntegerCollector()).result()); + + MathContext mc = new MathContext(7); + List lbd = Arrays.asList(new BigDecimal(1.1,mc),new BigDecimal(2.2,mc) + ,new BigDecimal(3.3,mc),new BigDecimal(4.4,mc)); + BigDecimal rbd = reduce(lbd,new BigDecimalAdder()); + System.out.println(rbd); + + System.out.println(fillter(lbd,new GreaterThan(new BigDecimal(3)))); + + List lbi = new ArrayList(); + BigInteger bi = BigInteger.valueOf(11); + for(int i=0;i<11;i++){ + lbi.add(bi); + bi = bi.nextProbablePrime(); + } + System.out.println(lbi); + + BigInteger rbi = reduce(lbi,new BigIntegerAdder()); + System.out.println(rbi); + + System.out.println(rbi.isProbablePrime(5)); + + List lal = Arrays.asList(new AtomicLong(11),new AtomicLong(47), + new AtomicLong(74),new AtomicLong(133)); + AtomicLong ral = reduce(lal,new AtomicLongAdder()); + System.out.println(ral); + System.out.println(transform(lbd,new BigDecimalUlp())); + } + + public static T reduce(Iterable seq,Combiner combiner){ + Iterator it = seq.iterator(); + if(it.hasNext()){ + T result = it.next(); + while(it.hasNext()){ + result = combiner.combine(result, it.next()); + } + return result; + } + return null; + } + + public static Collector forEach(Iterable seq,Collector func){ + for(T t:seq){ + func.function(t); + } + return func; + } + + public static List transform(Iterable seq,UnaryFunction func){ + List result = new ArrayList(); + for(T t:seq){ + result.add(func.function(t)); + } + return result; + } + + public static List fillter(Iterable seq,UnaryPredicated pred){ + List result = new ArrayList(); + for(T t:seq){ + if(pred.test(t)){ + result.add(t); + } + } + return result; + } + + static class IntegerAdder implements Combiner{ + + @Override + public Integer combine(Integer x, Integer y) { + return x+y; + } + + } + + static class IntegerSubtracter implements Combiner{ + + @Override + public Integer combine(Integer x, Integer y) { + return x-y; + } + + } + + static class BigDecimalAdder implements Combiner{ + + @Override + public BigDecimal combine(BigDecimal x, BigDecimal y) { + return x.add(y); + } + + } + + static class BigIntegerAdder implements Combiner{ + + @Override + public BigInteger combine(BigInteger x, BigInteger y) { + return x.add(y); + } + + } + + static class AtomicLongAdder implements Combiner{ + + @Override + public AtomicLong combine(AtomicLong x, AtomicLong y) { + return new AtomicLong(x.addAndGet(y.get())); + } + + } + + static class BigDecimalUlp implements UnaryFunction{ + + @Override + public BigDecimal function(BigDecimal x) { + return x.ulp(); + } + + } + + static class GreaterThan> implements UnaryPredicated{ + private T bound; + public GreaterThan(T bound){ + this.bound = bound; + } + @Override + public boolean test(T x) { + return x.compareTo(bound)>0; + } + + } + + static class MultiplyingIntegerCollector implements Collector{ + + private Integer val = 1; + @Override + public Integer function(Integer x) { + val *= x; + return val; + } + + @Override + public Integer result() { + return val; + } + + } +} +interface Combiner { + T combine(T x,T y); +} +interface UnaryFunction{ + R function(T x); +} +interface Collector extends UnaryFunction{ + T result(); +} +interface UnaryPredicated{ + boolean test(T x); +} diff --git a/src/btp/oneP/LatentReflection.java b/src/btp/oneP/LatentReflection.java new file mode 100644 index 0000000..f9b8bea --- /dev/null +++ b/src/btp/oneP/LatentReflection.java @@ -0,0 +1,58 @@ +package btp.oneP; + +import java.lang.reflect.Method; + +public class LatentReflection { + + public static void main(String[] args) { + CommunicateReflectively.perform(new SmartDog()); + CommunicateReflectively.perform(new Robott()); + CommunicateReflectively.perform(new Mime()); + } + +} + + +class Mime{ + public void walkAgainstTheWind(){} + public void sit(){ + System.out.println("Pretending to sit"); + } + public void pushInvisibleWalls(){} + public String toString(){ + return "Mime"; + } +} + +class SmartDog{ + public void speak(){ + System.out.println("Wolf!"); + } + public void sit(){ + System.out.println("Sitting!"); + } + public void reproduce(){} +} + +class CommunicateReflectively{ + public static void perform(Object speaker){ + Class clazz = speaker.getClass(); + try{ + try{ + Method speak = clazz.getMethod("speak"); + speak.invoke(speaker); + }catch(NoSuchMethodException e){ + System.out.println(speaker+" cannot speak"); + } + + try{ + Method sit = clazz.getMethod("sit"); + sit.invoke(speaker); + }catch(NoSuchMethodException e){ + System.out.println(speaker+" cannot sit"); + } + }catch(Exception e){ + throw new RuntimeException(speaker.toString(),e); + } + } +} \ No newline at end of file From 812aa12a3c5441a442f662919ab35459e166924d Mon Sep 17 00:00:00 2001 From: btp <842297171@qq.com> Date: Sat, 3 Jun 2017 23:37:22 +0800 Subject: [PATCH 4/7] Chapter-16-Arrays-btp170603 --- src/btp/oneP/ArrayOfGenerics.java | 31 ++++++++++ src/btp/oneP/ArrayOptions.java | 56 +++++++++++++++++++ src/btp/oneP/ArrayTest.java | 16 ++++++ src/btp/oneP/ContainerComparison.java | 43 ++++++++++++++ src/btp/oneP/IceCream.java | 40 +++++++++++++ .../oneP/MultidimensionalPrimitiveArray.java | 14 +++++ src/btp/oneP/ParameterizedArrayType.java | 34 +++++++++++ src/btp/oneP/ThreeWithNew.java | 19 +++++++ 8 files changed, 253 insertions(+) create mode 100644 src/btp/oneP/ArrayOfGenerics.java create mode 100644 src/btp/oneP/ArrayOptions.java create mode 100644 src/btp/oneP/ArrayTest.java create mode 100644 src/btp/oneP/ContainerComparison.java create mode 100644 src/btp/oneP/IceCream.java create mode 100644 src/btp/oneP/MultidimensionalPrimitiveArray.java create mode 100644 src/btp/oneP/ParameterizedArrayType.java create mode 100644 src/btp/oneP/ThreeWithNew.java diff --git a/src/btp/oneP/ArrayOfGenerics.java b/src/btp/oneP/ArrayOfGenerics.java new file mode 100644 index 0000000..8ab2dc6 --- /dev/null +++ b/src/btp/oneP/ArrayOfGenerics.java @@ -0,0 +1,31 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class ArrayOfGenerics { + + public static void main(String[] args) { + //编译期不能实例化泛型数组,但是可以创建泛型数组的引用 + List[] ls; + List[] la = new List[10]; + ls = (List[])la; + ls[0] = new ArrayList(Arrays.asList("hehe","keke","xixi")); + //ls[1] = new ArrayList(); + + Object[] objects = ls; + objects[1] = new ArrayList(Arrays.asList(1,2,3,4,5)); + System.out.println(Arrays.toString(la)); + System.out.println(la.getClass().getName()); + System.out.println(Arrays.toString(ls)); + System.out.println(ls.getClass().getName()); + System.out.println(Arrays.toString(objects)); + System.out.println(objects.getClass().getName()); + List[] spheres = (List[])new List[10]; + for(int i=0;i<10;i++){ + spheres[i] = new ArrayList(); + } + } + +} diff --git a/src/btp/oneP/ArrayOptions.java b/src/btp/oneP/ArrayOptions.java new file mode 100644 index 0000000..2686afc --- /dev/null +++ b/src/btp/oneP/ArrayOptions.java @@ -0,0 +1,56 @@ +package btp.oneP; + +import java.util.Arrays; + +public class ArrayOptions { + + public static void main(String[] args) { + BerylliumSphere[] a = null; + BerylliumSphere[] b = new BerylliumSphere[5]; + System.out.println(a); + System.out.println(b); + System.out.println(Arrays.toString(b)); + + BerylliumSphere[] c = new BerylliumSphere[4]; + for(int i=0;i sphereList = new ArrayList(); + for(int i=0;i<5;i++){ + sphereList.add(new BerylliumSphere()); + } + System.out.println(sphereList); + System.out.println(sphereList.get(4)); + + int[] integers = {0,1,2,3,4,5}; + System.out.println(integers); + System.out.println(integers[4]); + + List intList = new ArrayList(Arrays.asList(0,1,2,3,4,5)); + intList.add(97); + System.out.println(intList); + System.out.println(intList.get(4)); + + } + +} + +class BerylliumSphere{ + private static long counter; + private final long id = counter++; + public String toString(){ + return "Sphere"+id; + } +} diff --git a/src/btp/oneP/IceCream.java b/src/btp/oneP/IceCream.java new file mode 100644 index 0000000..da7415b --- /dev/null +++ b/src/btp/oneP/IceCream.java @@ -0,0 +1,40 @@ +package btp.oneP; + +import java.util.Arrays; +import java.util.Random; + +public class IceCream { + + private static Random rand = new Random(47); + static final String[] FLAVORS = { + "Chocolate","Strawberry","Vanilla","Mint Chip", + "Mocha Almond Fudge","Rum Raisin","Praline","Mud" + }; + + public static String[] flavorSet(int n){ + if(n>FLAVORS.length){ + throw new IllegalArgumentException("Set too big"); + } + String[] results = new String[n]; + boolean[] picked = new boolean[FLAVORS.length]; + for(int i=0;i().f(ints); + System.out.println(Arrays.toString(ints2)); + System.out.println(ints == ints2); + + Double[] doubles2 = new ClassParameter().f(doubles); + System.out.println(Arrays.toString(doubles2)); + + ints = MethodParameter.f(ints); + System.out.println(Arrays.toString(ints)); + doubles = MethodParameter.f(doubles); + } + +} + +class ClassParameter{ + public T[] f(T[] args){ + return args; + } +} + +class MethodParameter{ + public static T[] f(T[] arg){ + return arg; + } +} \ No newline at end of file diff --git a/src/btp/oneP/ThreeWithNew.java b/src/btp/oneP/ThreeWithNew.java new file mode 100644 index 0000000..5843303 --- /dev/null +++ b/src/btp/oneP/ThreeWithNew.java @@ -0,0 +1,19 @@ +package btp.oneP; + +import java.util.Arrays; + +public class ThreeWithNew { + + public static void main(String[] args) { + int[][][] a = new int[2][2][4]; + System.out.println(a); + System.out.println(Arrays.toString(a)); + System.out.println("a.length:"+a.length); + System.out.println(Arrays.toString(a[0])); + System.out.println("a[0].length:"+a[0].length); + System.out.println(Arrays.toString(a[1])); + System.out.println("a[1].length:"+a[1].length); + System.out.println(Arrays.toString(a[0][1])); + } + +} From 233b2a0d62490525582e6a3ba4db425b0062900d Mon Sep 17 00:00:00 2001 From: btp <842297171@qq.com> Date: Sun, 18 Jun 2017 22:20:12 +0800 Subject: [PATCH 5/7] Chapter-17-Collections-btp170618 --- src/btp/oneP/CollectionDataTest.java | 44 +++++++++++ src/btp/oneP/FillingLists.java | 30 ++++++++ src/btp/oneP/MapDataTest.java | 111 +++++++++++++++++++++++++++ 3 files changed, 185 insertions(+) create mode 100644 src/btp/oneP/CollectionDataTest.java create mode 100644 src/btp/oneP/FillingLists.java create mode 100644 src/btp/oneP/MapDataTest.java diff --git a/src/btp/oneP/CollectionDataTest.java b/src/btp/oneP/CollectionDataTest.java new file mode 100644 index 0000000..6dc1c1e --- /dev/null +++ b/src/btp/oneP/CollectionDataTest.java @@ -0,0 +1,44 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.Set; + +public class CollectionDataTest { + + public static void main(String[] args) { + Set set = new LinkedHashSet(new CollectionData(new Government(),7)); + set.addAll(CollectionData.list(new Government(), 7)); + System.out.println(set); + } + +} + +class CollectionData extends ArrayList { + public CollectionData(GeneratorN gen,int quantity){ + for(int i=0;i CollectionData list(GeneratorN gen,int quantity){ + return new CollectionData(gen,quantity); + } +} + +interface GeneratorN{ + T next(); +} + +class Government implements GeneratorN{ + String[] foundation = "you are a hero not a coward".split(" "); + private int index; + @Override + public String next() { + // TODO Auto-generated method stub + return foundation[index++]; + } + +} + + diff --git a/src/btp/oneP/FillingLists.java b/src/btp/oneP/FillingLists.java new file mode 100644 index 0000000..abeb033 --- /dev/null +++ b/src/btp/oneP/FillingLists.java @@ -0,0 +1,30 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class FillingLists { + + @SuppressWarnings("unchecked") + public static void main(String[] args) { + List list = (List) Collections.nCopies(4, new StringAddress("hehe")); + System.out.println(list); + list = new ArrayList(list); + System.out.println(list); + + Collections.fill(list, new StringAddress("xixi")); + System.out.println(list); + } + +} + +class StringAddress{ + private String s; + public StringAddress(String s){ + this.s = s; + } + public String toString(){ + return super.toString()+" "+s; + } +} diff --git a/src/btp/oneP/MapDataTest.java b/src/btp/oneP/MapDataTest.java new file mode 100644 index 0000000..5588eaa --- /dev/null +++ b/src/btp/oneP/MapDataTest.java @@ -0,0 +1,111 @@ +package btp.oneP; + +import java.util.Iterator; +import java.util.LinkedHashMap; + +public class MapDataTest { + + public static void main(String[] args) { + System.out.println(MapData.map(new Letters(), 11)); + + System.out.println(MapData.map(new Letters(), "Pop")); + } + +} + + +class PairN{ + public final K key; + public final V value; + public PairN(K k,V v){ + this.key = k; + this.value = v; + } +} + +class MapData extends LinkedHashMap{ + public MapData(GeneratorN> gen,int quantity){ + for(int i=0;i p = gen.next(); + this.put(p.key, p.value); + } + } + + public MapData(GeneratorN genK,GeneratorN genV,int quantity){ + for(int i=0;i genK,V value,int quantity){ + for(int i=0;i genK,GeneratorN genV){ + for(K key:genK){ + this.put(key,genV.next()); + } + } + + public MapData(Iterable genK, V value){ + for(K key:genK){ + this.put(key, value); + } + } + + public static MapData map(GeneratorN> gen,int quantity){ + return new MapData(gen,quantity); + } + + public static MapData map(GeneratorN genK,GeneratorN genV,int quantity){ + return new MapData(genK,genV,quantity); + } + + public static MapData map(GeneratorN genK,V value,int quantity){ + return new MapData(genK,value,quantity); + } + + public static MapData map(Iterable genK,GeneratorN genV){ + return new MapData(genK,genV); + } + + public static MapData map(Iterable genK,V value){ + return new MapData(genK,value); + } +} + +class Letters implements GeneratorN>, + Iterable{ + + private int size = 9; + private int number = 1; + private char letter = 'A'; + + @Override + public PairN next() { + return new PairN(number++,""+letter++); + } + + @Override + public Iterator iterator() { + // TODO Auto-generated method stub + return new Iterator(){ + + @Override + public boolean hasNext() { + // TODO Auto-generated method stub + return number < size; + } + + @Override + public Integer next() { + // TODO Auto-generated method stub + return number++; + } + + }; + } + +} \ No newline at end of file From cdaa8e02b7b6cdf1820baa39bdb107edccec9f1c Mon Sep 17 00:00:00 2001 From: btp <842297171@qq.com> Date: Mon, 10 Jul 2017 20:23:51 +0800 Subject: [PATCH 6/7] Chapter 17 collections btp170710 --- Study.iml | 12 ++ src/btp/oneP/ABtpTest.java | 10 +- src/btp/oneP/CollectionMethod.java | 53 ++++++++ src/btp/oneP/CountingIntegerList.java | 33 +++++ src/btp/oneP/CountingMapData.java | 61 +++++++++ src/btp/oneP/Countries.java | 145 ++++++++++++++++++++ src/btp/oneP/Lists.java | 113 +++++++++++++++ src/btp/oneP/PDFTest.java | 189 ++++++++++++++++++++++++++ src/btp/oneP/SetFillList.java | 22 +++ src/btp/oneP/Unsupported.java | 67 +++++++++ 10 files changed, 703 insertions(+), 2 deletions(-) create mode 100644 Study.iml create mode 100644 src/btp/oneP/CollectionMethod.java create mode 100644 src/btp/oneP/CountingIntegerList.java create mode 100644 src/btp/oneP/CountingMapData.java create mode 100644 src/btp/oneP/Countries.java create mode 100644 src/btp/oneP/Lists.java create mode 100644 src/btp/oneP/PDFTest.java create mode 100644 src/btp/oneP/SetFillList.java create mode 100644 src/btp/oneP/Unsupported.java diff --git a/Study.iml b/Study.iml new file mode 100644 index 0000000..b8db988 --- /dev/null +++ b/Study.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/btp/oneP/ABtpTest.java b/src/btp/oneP/ABtpTest.java index be23f00..36bdcce 100644 --- a/src/btp/oneP/ABtpTest.java +++ b/src/btp/oneP/ABtpTest.java @@ -3,6 +3,8 @@ import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; import java.util.Scanner; public class ABtpTest { @@ -11,13 +13,17 @@ public static void main(String[] args) { PrintStream p = System.out; Scanner sc =new Scanner(System.in); try{ - ArrayList as = returnArray(); + /*ArrayList as = returnArray(); ArrayList ass = (ArrayList)as; p.println(ass); as = returnArrayNew(); p.println(as); ass = (ArrayList)as; - p.println(ass); + p.println(ass);*/ + + List myIntList = new LinkedList();//1 + myIntList.add(new Integer(0));//2 + Integer x = (Integer) myIntList.iterator().next();//3 }catch(Exception e){ e.printStackTrace(); }finally{ diff --git a/src/btp/oneP/CollectionMethod.java b/src/btp/oneP/CollectionMethod.java new file mode 100644 index 0000000..f4b9778 --- /dev/null +++ b/src/btp/oneP/CollectionMethod.java @@ -0,0 +1,53 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +public class CollectionMethod { + + public static void main(String[] args) { + Collection c = new ArrayList(); + c.addAll(Countries.names(6)); + c.add("ten"); + c.add("eleven"); + System.out.println(c); + + Object[] array = c.toArray(); + String[] str = c.toArray(new String[0]); + + System.out.println(Arrays.toString(array)); + System.out.println(Arrays.toString(str)); + + System.out.println("Collections.max(c) = "+Collections.max(c)); + System.out.println("Collections.min(c) = "+Collections.min(c)); + + Collection c2 = new ArrayList(); + c2.addAll(Countries.names(6)); + c.addAll(c2); + System.out.println(c); + c.remove(Countries.DATA[0][0]); + System.out.println(c); + c.removeAll(c2); + System.out.println(c); + c.addAll(c2); + System.out.println(c); + String val = Countries.DATA[3][0]; + System.out.println("c.contains("+val+")="+c.contains(val)); + System.out.println("c.containsAll(c2)="+c.containsAll(c2)); + + Collection c3 = ((List)c).subList(3, 5); + c2.retainAll(c3); + System.out.println(c2); + c2.removeAll(c3); + System.out.println("c2.isEmpty()="+c2.isEmpty()); + c = new ArrayList(); + c.addAll(Countries.names(6)); + System.out.println(c); + c.clear(); + System.out.println("after c.clear():"+c); + } + +} diff --git a/src/btp/oneP/CountingIntegerList.java b/src/btp/oneP/CountingIntegerList.java new file mode 100644 index 0000000..5eae6da --- /dev/null +++ b/src/btp/oneP/CountingIntegerList.java @@ -0,0 +1,33 @@ +package btp.oneP; + +import java.util.AbstractList; + +public class CountingIntegerList extends AbstractList{ + + public static void main(String[] args) { + // TODO Auto-generated method stub + //构造函数构造对象时里面还没有值,都是null,在调用toString函数的时候, + //toString函数内使用Iterator遍历集合,next()时调用了get(index) + //所以是边赋值边打印 + System.out.println(new CountingIntegerList(30)); + } + + + private int size; + public CountingIntegerList(int size){ + this.size = size<0?0:size; + } + + @Override + public Integer get(int index) { + // TODO Auto-generated method stub + return Integer.valueOf(index); + } + + @Override + public int size() { + // TODO Auto-generated method stub + return size; + } + +} diff --git a/src/btp/oneP/CountingMapData.java b/src/btp/oneP/CountingMapData.java new file mode 100644 index 0000000..23c8df8 --- /dev/null +++ b/src/btp/oneP/CountingMapData.java @@ -0,0 +1,61 @@ +package btp.oneP; + +import java.util.AbstractMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +public class CountingMapData extends AbstractMap{ + + public static void main(String...args){ + System.out.println(new CountingMapData(60)); + } + + private int size; + private static String[] chars = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z".split(" "); + public CountingMapData(int size){ + this.size = size<0?0:size; + } + + private static class Entry implements Map.Entry{ + int index; + Entry(int index){ + this.index = index; + } + public boolean equals(Object o){ + return Integer.valueOf(index).equals(o); + } + @Override + public Integer getKey() { + // TODO Auto-generated method stub + return index; + } + + @Override + public String getValue() { + // TODO Auto-generated method stub + return chars[index%chars.length]+Integer.toString(index/chars.length); + } + + @Override + public String setValue(String value) { + // TODO Auto-generated method stub + return null; + } + + public int hashCode(){ + return Integer.valueOf(index).hashCode(); + } + } + + @Override + public Set> entrySet() { + // TODO Auto-generated method stub + Set> entries = new LinkedHashSet>(); + for(int i=0;i(capitals(3))); + System.out.println(new LinkedHashMap(capitals(3))); + System.out.println(new TreeMap(capitals(3))); + System.out.println(new Hashtable(capitals(3))); + System.out.println(new HashSet(names(6))); + System.out.println(new LinkedHashSet(names(6))); + System.out.println(new TreeSet(names(6))); + System.out.println(new ArrayList(names(6))); + System.out.println(new LinkedList(names(6))); + System.out.println(capitals().get("ALGERIA")); + } + + public static final String[][] DATA = { + {"ALGERIA","Algiers"},{"CHINA","Beijing"}, + {"Japan","Tokoy"},{"America","Washington"} + }; + private static class FlyweightMap extends AbstractMap{ + private static class Entry implements Map.Entry{ + int index; + Entry(int index){ + this.index = index; + } + public boolean equals(Object o){ + return DATA[index][0].equals(o); + } + @Override + public String getKey() { + // TODO Auto-generated method stub + return DATA[index][0]; + } + + @Override + public String getValue() { + return DATA[index][1]; + } + + @Override + public String setValue(String value) { + // TODO Auto-generated method stub + return null; + } + + public int hashCode(){ + return DATA[index][0].hashCode(); + } + } + + static class EntrySet extends AbstractSet>{ + private int size; + EntrySet(int size){ + if(size < 0){ + this.size = 0; + }else if(size > DATA.length){ + this.size = DATA.length; + }else{ + this.size = size; + } + } + public int size(){ + return size; + } + + @Override + public Iterator> iterator() { + // TODO Auto-generated method stub + return new Iter(); + } + + private class Iter implements Iterator>{ + private Entry entry = new Entry(-1); + @Override + public boolean hasNext() { + // TODO Auto-generated method stub + return entry.index < size - 1; + } + + @Override + public java.util.Map.Entry next() { + entry.index++; + return entry; + } + + } + } + + private static Set> entries = new EntrySet(DATA.length); + @Override + public Set> entrySet() { + return entries; + } + + } + + + + + + + static Map select(final int size){ + return new FlyweightMap(){ + public Set> entrySet(){ + return new EntrySet(size); + } + }; + } + + static Map map = new FlyweightMap(); + public static Map capitals(){ + return map; + } + public static Map capitals(int size){ + return select(size); + } + static List names = new ArrayList(map.keySet()); + + public static List names(){ + return names; + } + public static List names(int size){ + return new ArrayList(select(size).keySet()); + } +} diff --git a/src/btp/oneP/Lists.java b/src/btp/oneP/Lists.java new file mode 100644 index 0000000..d57237e --- /dev/null +++ b/src/btp/oneP/Lists.java @@ -0,0 +1,113 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; + +public class Lists { + + private static boolean b; + private static String s; + private static int i; + private static Iterator it; + private static ListIterator lit; + public static void basicTest(List a){ + a.add(1,"x"); + a.add("x"); + a.addAll(Countries.names(25)); + a.addAll(3,Countries.names(25)); + b = a.contains("1"); + b = a.containsAll(Countries.names(25)); + s = a.get(1); + i = a.indexOf("1"); + b = a.isEmpty(); + it = a.iterator(); + lit = a.listIterator(); + lit = a.listIterator(3); + i = a.lastIndexOf("1"); + a.remove(1); + a.remove("3"); + a.set(1, "y"); + + a.retainAll(Countries.names(25)); + a.removeAll(Countries.names(25)); + i = a.size(); + a.clear(); + } + + public static void iterMotion(List a){ + ListIterator it = a.listIterator(); + b = it.hasNext(); + b = it.hasPrevious(); + s = it.next(); + i = it.nextIndex(); + s = it.previous(); + i = it.previousIndex(); + } + + public static void iterManipulation(List a){ + ListIterator it = a.listIterator(); + it.add("47"); + it.next(); + it.remove(); + it.next(); + it.set("47"); + } + + public static void testVisual(List a){ + System.out.println(a); + List b = Countries.names(25); + System.out.println("b = "+b); + a.addAll(b); + a.addAll(b); + System.out.println(a); + + ListIterator x = a.listIterator(a.size()/2); + x.add("one"); + System.out.println(a); + System.out.println(x.next()); + x.remove(); + System.out.println(x.next()); + x.set("47"); + System.out.println(a); + x = a.listIterator(a.size()); + while(x.hasPrevious()){ + System.out.println(x.previous() + " "); + } + System.out.println(); + System.out.println("testVisual finished"); + } + + public static void testLinkedList(){ + LinkedList ll = new LinkedList(); + ll.addAll(Countries.names(25)); + System.out.println(ll); + ll.addFirst("one"); + ll.addFirst("two"); + System.out.println(ll); + System.out.println(ll.getFirst()); + System.out.println(ll.removeFirst()); + System.out.println(ll.removeFirst()); + System.out.println(ll.removeLast()); + System.out.println(ll); + } + + public static void main(String[] args) { + /*basicTest(new LinkedList(Countries.names(25))); + basicTest(new ArrayList(Countries.names(25))); + iterMotion(new LinkedList(Countries.names(25))); + iterMotion(new ArrayList(Countries.names(25))); + iterManipulation(new LinkedList(Countries.names(25))); + iterManipulation(new ArrayList(Countries.names(25))); + testVisual(new LinkedList(Countries.names(25))); + testLinkedList();*/ + List list = new ArrayList(); + list.add("A"); + list.add("B"); + list.set(0, "C"); + System.out.println(list); + } + +} diff --git a/src/btp/oneP/PDFTest.java b/src/btp/oneP/PDFTest.java new file mode 100644 index 0000000..ca4b7d8 --- /dev/null +++ b/src/btp/oneP/PDFTest.java @@ -0,0 +1,189 @@ +package btp.oneP; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintWriter; + +public class PDFTest { + public static void main(String...args){ + Pdf2htmlEXUtil.pdf2html("C:\\Users\\dell\\Desktop\\pdf转html\\pdf2htmlEX-v1.0\\pdf2htmlEX.exe","C:\\Users\\dell\\Desktop\\匹配确认书.pdf","C:\\Users\\dell\\Desktop\\pdf转html","my.html"); + } + +} + + + + + + +/** + * @author liuzhengyong + * @version 1.0 时间:2013-12-30 下午2:24:10 pdf文件转html工具类 + */ +class Pdf2htmlEXUtil { + /** + * 调用pdf2htmlEX将pdf文件转换为html文件 + * + * @param exeFilePath + * pdf2htmlEX.exe文件路径 + * @param pdfFile + * pdf文件绝对路径 + * @param [destDir] 生成的html文件存放路径 + * @param htmlName + * 生成的html文件名称 + * @return + */ + public static boolean pdf2html(String exeFilePath, String pdfFile, + String destDir, String htmlFileName) { + if (!(exeFilePath != null && !"".equals(exeFilePath) && pdfFile != null + && !"".equals(pdfFile) && htmlFileName != null && !"" + .equals(htmlFileName))) { + System.out.println("传递的参数有误!"); + return false; + } + Runtime rt = Runtime.getRuntime(); + StringBuilder command = new StringBuilder(); + command.append(exeFilePath).append(" "); + if (destDir != null && !"".equals(destDir.trim()))// 生成文件存放位置,需要替换文件路径中的空格 + command.append("--dest-dir ").append(destDir.replace(" ", "\" \"")) + .append(" "); + command.append("--optimize-text 1 ");// 尽量减少用于文本的HTML元素的数目 (default: 0) + command.append("--zoom 1.4 "); + command.append("--process-outline 0 ");// html中显示链接:0——false,1——true + command.append("--font-format woff ");// 嵌入html中的字体后缀(default ttf) + // ttf,otf,woff,svg + command.append(pdfFile.replace(" ", "\" \"")).append(" ");// 需要替换文件路径中的空格 + if (htmlFileName != null && !"".equals(htmlFileName.trim())) { + command.append(htmlFileName); + if (htmlFileName.indexOf(".html") == -1) + command.append(".html"); + } + try { + System.out.println("Command:" + command.toString()); + Process p = rt.exec(command.toString()); + StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), + "ERROR"); + // 开启屏幕标准错误流 + errorGobbler.start(); + StreamGobbler outGobbler = new StreamGobbler(p.getInputStream(), + "STDOUT"); + // 开启屏幕标准输出流 + outGobbler.start(); + int w = p.waitFor(); + int v = p.exitValue(); + if (w == 0 && v == 0) { + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public static boolean pdf2html_linux(String pdfFile, String destDir, + String htmlFileName) { + if (!(pdfFile != null && !"".equals(pdfFile) && htmlFileName != null && !"" + .equals(htmlFileName))) { + System.out.println("传递的参数有误!"); + return false; + } + Runtime rt = Runtime.getRuntime(); + StringBuilder command = new StringBuilder(); + command.append("pdf2htmlEX").append(" "); + if (destDir != null && !"".equals(destDir.trim()))// 生成文件存放位置,需要替换文件路径中的空格 + command.append("--dest-dir ").append(destDir.replace(" ", "\" \"")) + .append(" "); + command.append("--optimize-text 1 ");// 尽量减少用于文本的HTML元素的数目 (default: 0) + command.append("--process-outline 0 ");// html中显示链接:0——false,1——true + command.append("--font-format woff ");// 嵌入html中的字体后缀(default ttf) + // ttf,otf,woff,svg + command.append(pdfFile.replace(" ", "\" \"")).append(" ");// 需要替换文件路径中的空格 + if (htmlFileName != null && !"".equals(htmlFileName.trim())) { + command.append(htmlFileName); + if (htmlFileName.indexOf(".html") == -1) + command.append(".html"); + } + try { + System.out.println("Command:" + command.toString()); + Process p = rt.exec(command.toString()); + StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), + "ERROR"); + // 开启屏幕标准错误流 + errorGobbler.start(); + StreamGobbler outGobbler = new StreamGobbler(p.getInputStream(), + "STDOUT"); + // 开启屏幕标准输出流 + outGobbler.start(); + int w = p.waitFor(); + int v = p.exitValue(); + if (w == 0 && v == 0) { + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + +} + + + +/** + * 用于处理Runtime.getRuntime().exec产生的错误流及输出流 + * + * @author shaojing + * + */ +class StreamGobbler extends Thread { + InputStream is; + String type; + OutputStream os; + + public StreamGobbler(InputStream is, String type) { + this(is, type, null); + } + + StreamGobbler(InputStream is, String type, OutputStream redirect) { + this.is = is; + this.type = type; + this.os = redirect; + } + + public void run() { + InputStreamReader isr = null; + BufferedReader br = null; + PrintWriter pw = null; + try { + if (os != null) + pw = new PrintWriter(os); + isr = new InputStreamReader(is); + br = new BufferedReader(isr); + String line = null; + while ((line = br.readLine()) != null) { + if (pw != null) + pw.println(line); + System.out.println(type + ">" + line); + } + if (pw != null) + pw.flush(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } finally { + try { + if (pw != null) + pw.close(); + if (br != null) + br.close(); + if (isr != null) + isr.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } +} \ No newline at end of file diff --git a/src/btp/oneP/SetFillList.java b/src/btp/oneP/SetFillList.java new file mode 100644 index 0000000..483f3a8 --- /dev/null +++ b/src/btp/oneP/SetFillList.java @@ -0,0 +1,22 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class SetFillList { + + public static void main(String[] args) { + List c = Collections.nCopies(5, new String("hello")); + Set s = new HashSet(c); + System.out.println(s); + List l = new ArrayList(s); + System.out.println(l); + Collections.fill(l, new String("world")); + s = new HashSet(l); + System.out.println(s); + } + +} diff --git a/src/btp/oneP/Unsupported.java b/src/btp/oneP/Unsupported.java new file mode 100644 index 0000000..8f6d6fa --- /dev/null +++ b/src/btp/oneP/Unsupported.java @@ -0,0 +1,67 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +public class Unsupported { + + static void test(String msg,List list){ + System.out.println("--- "+msg+" ---"); + Collection c = list; + Collection sublist = list.subList(1, 8); + Collection c2 = new ArrayList(sublist); + + try{ + c.retainAll(c2); + }catch(Exception e){ + System.out.println("retainAll():"+e); + } + + try{ + c.removeAll(c2); + }catch(Exception e){ + System.out.println("removeAll():"+e); + } + + try{ + c.clear(); + }catch(Exception e){ + System.out.println("clear():"+e); + } + + try{ + c.add("X"); + }catch(Exception e){ + System.out.println("add():"+e); + } + + try{ + c.addAll(c2); + }catch(Exception e){ + System.out.println("addAll():"+e); + } + + try{ + c.remove("C"); + }catch(Exception e){ + System.out.println("remove():"+e); + } + + try{ + list.set(0, "X"); + }catch(Exception e){ + System.out.println("List.set():"+e); + } + } + public static void main(String[] args) { + // TODO Auto-generated method stub + List list = Arrays.asList("A B C D E F G H I J K L".split(" ")); + test("Modifiable Copy",new ArrayList(list)); + test("Arrays.asList()",list); + test("unmodifiableList()",Collections.unmodifiableList(new ArrayList(list))); + } + +} From 430fb6e63fd78b5456136d9265f0acf0fc6eae69 Mon Sep 17 00:00:00 2001 From: btp <842297171@qq.com> Date: Tue, 11 Jul 2017 21:10:08 +0800 Subject: [PATCH 7/7] Chapter 17 collections btp170711 --- src/btp/oneP/TypesForSets.java | 72 ++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/btp/oneP/TypesForSets.java diff --git a/src/btp/oneP/TypesForSets.java b/src/btp/oneP/TypesForSets.java new file mode 100644 index 0000000..4a3a6ac --- /dev/null +++ b/src/btp/oneP/TypesForSets.java @@ -0,0 +1,72 @@ +package btp.oneP; + +import java.util.HashSet; +import java.util.Set; + +public class TypesForSets { + static Set fill(Set set,Class type){ + try{ + for(int i=0;i<10;i++){ + set.add(type.getConstructor(int.class).newInstance(i)); + } + }catch(Exception e){ + throw new RuntimeException(e); + } + return set; + } + + static void test(Set set,Class type){ + fill(set,type);fill(set,type);fill(set,type); + System.out.println(set); + } + public static void main(String[] args) { + test(new HashSet(),HashType.class); + test(new HashSet(),HashType.class); + test(new HashSet(),HashType.class); + test(new HashSet(),HashType.class); + test(new HashSet(),HashType.class); + test(new HashSet(),HashType.class); + test(new HashSet(),HashType.class); + } + +} + +class SetType{ + int i; + public SetType(int n){ + i = n; + } + public boolean equals(Object o){ + return o instanceof SetType && (i == ((SetType)o).i); + } + public String toString(){ + return Integer.toString(i); + } +} + +class HashType extends SetType{ + + public HashType(int n) { + super(n); + // TODO Auto-generated constructor stub + } + + public int hashCode(){ + return i; + } +} + +class TreeType extends SetType implements Comparable{ + + public TreeType(int n) { + super(n); + // TODO Auto-generated constructor stub + } + + @Override + public int compareTo(TreeType o) { + // TODO Auto-generated method stub + return (o.i