class Cat {
}
class Dog {
}
class Pet{
}
public class CheckedList {
static void oldStyleMethod(List list) {
list.add(new Cat());
}
public static void main(String[] args) {
List dogs = new ArrayList<>();
oldStyleMethod(dogs);
//悄悄地接受一只cat
List dogList = Collections.checkedList(new ArrayList(), Dog.class);
try {
oldStyleMethod(dogList);
//引发异常
} catch (Exception e) {
System.err.println(e);
}
// 派生类型工作正常
List pets = Collections.checkedList(new ArrayList(), Pet.class);
}
}
//运行结果为
java.lang.ClassCastException: Attempt to insert class generic.Cat element into collection with element type class generic.Dog
public interface ProcessorTest {
void process(List list) throws E;
}
class ProicessRunner extends ArrayList> {
List processAll() throws E {
List list = new ArrayList<>();
for (ProcessorTest processor : this) {
processor.process(list);
}
return list;
}
}
class Failurel extends Exception {
}
class Processor1 implements ProcessorTest {
static int count = 3;
@Override
public void process(List list) throws Failurel {
if (count-- >1){
list.add("hep!");
}else {
list.add("ho!");
}
if (count<0){
throw new Failurel();
}
}
}
class Failure2 extends Exception{}
class Processor2 implements ProcessorTest{
static int count = 2;
@Override
public void process(List list) throws Failure2 {
if (count-- >1){
list.add(47);
}else {
list.add(11);
}
if (count<0){
throw new Failure2();
}
}
}
class ThrowGenericException{
public static void main(String[] args) {
ProicessRunner processors=new ProicessRunner<>();
for (int i = 0; i < 3; i++) {
processors.add(new Processor1());
}
try {
System.out.println(processors.processAll());
} catch (Failurel failurel) {
System.err.println(failurel);
}
ProicessRunner processors1=new ProicessRunner<>();
for (int i = 0; i < 3; i++) {
processors1.add(new Processor2());
}
try {
System.out.println(processors1.processAll());
} catch (Failure2 failure2) {
System.out.println(failure2);
}
}
}
//运行结果为
[hep!, hep!, ho!]
generic.Failure2
public interface TimeStamped {
long getStamp();
}
class TimeStampedImp implements TimeStamped {
private final long timeStamp;
public TimeStampedImp(long timeStamp) {
this.timeStamp = timeStamp;
}
@Override
public long getStamp() {
return timeStamp;
}
}
interface SerialNumbered {
long getSerialNumber();
}
class SerialNumberedImpl implements SerialNumbered {
private static long counter = 1;
private final long serialNumber = counter++;
@Override
public long getSerialNumber() {
return serialNumber;
}
}
interface Basic{
void set(String str);
String get();
}
class BasicImpl implements Basic{
private String string;
@Override
public void set(String str) {
this.string=str;
}
@Override
public String get() {
return string;
}
}
class Maxin extends BasicImpl implements TimeStamped,SerialNumbered{
private TimeStamped timeStamped=new TimeStampedImp(System.currentTimeMillis());
private SerialNumbered serialNumbered=new SerialNumberedImpl();
@Override
public long getStamp() {
return timeStamped.getStamp();
}
@Override
public long getSerialNumber() {
return serialNumbered.getSerialNumber();
}
}
class Minxins{
public static void main(String[] args) {
Maxin maxin1=new Maxin();
Maxin maxin2=new Maxin();
maxin1.set("test string 1");
maxin2.set("test string 2");
System.out.println(maxin1.get() +" "+maxin1.getStamp()+" "+maxin1.getSerialNumber());
System.out.println(maxin2.get() +" "+maxin2.getStamp()+" "+maxin2.getSerialNumber());
}
}
//运行结果为
test string 1 1594345540399 1
test string 2 1594345540399 2
public class BasicExamples {
private String string;
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
}
class Decorator extends BasicExamples {
private BasicExamples basicExamples;
public Decorator(BasicExamples basicExamples) {
this.basicExamples = basicExamples;
}
@Override
public String getString() {
return basicExamples.getString();
}
@Override
public void setString(String string) {
basicExamples.setString(string);
}
}
class TimeStampedExamples extends Decorator {
private final long timeStamp;
public TimeStampedExamples(BasicExamples basicExamples) {
super(basicExamples);
this.timeStamp = System.currentTimeMillis();
}
long getTimeStamp() {
return timeStamp;
}
}
class SerialNumberExamples extends Decorator {
private static long counter = 1;
private final long serialNumber = counter++;
public SerialNumberExamples(BasicExamples basicExamples) {
super(basicExamples);
}
long getSerialNumber(){
return serialNumber;
}
}
class Decoration{
public static void main(String[] args) {
TimeStampedExamples timeStampedExamples=new TimeStampedExamples(new BasicExamples());
TimeStampedExamples timeStampedExamples1=new TimeStampedExamples(new SerialNumberExamples(new BasicExamples()));
//timeStampedExamples1.getSerialNumber(); 无法使用
SerialNumberExamples serialNumberExamples=new SerialNumberExamples(new BasicExamples());
SerialNumberExamples serialNumberExamples1=new SerialNumberExamples(new TimeStampedExamples(new BasicExamples()));
//serialNumberExamples1.getTimeStamp(); 无法使用
}
}
public interface Performs {
void speak();
void sit();
}
class PerformsDog implements Performs{
@Override
public void speak() {
System.out.println("Woof!");
}
@Override
public void sit() {
System.out.println("Sitting");
}
}
class Robot implements Performs{
@Override
public void speak() {
System.out.println("Click");
}
@Override
public void sit() {
System.out.println("Clank");
}
}
class Communicate{
static void performs(T t){
t.sit();
t.speak();
}
}
class DogsAndRobots{
public static void main(String[] args) {
Robot robot = new Robot();
PerformsDog performsDog=new PerformsDog();
Communicate.performs(performsDog);
Communicate.performs(robot);
}
}
//运行结果为
Sitting
Woof!
Clank
Click
class ComunicateSimply{
static void perform(Performs performs){
performs.speak();
performs.sit();
}
public static void main(String[] args) {
perform(new Robot());
perform(new PerformsDog());
}
}
//运行结果为
Click
Clank
Woof!
Sitting
反射
public class Mime {
public void walkAgainstTheWind() {
}
public void sit() {
System.out.println("Mime sit()");
}
public void pushInvisibleWalls() {
}
@Override
public String toString() {
return "Mime";
}
}
class SmartDog {
public void speak() {
System.out.println("Woof!");
}
public void sit() {
System.out.println("Sitting");
}
public void reproduce() {
}
}
class CommunicateReflectively {
static void performs(Object object) {
Class> aClass = object.getClass();
try {
//通过反射获取 speak方法
try {
Method speak = aClass.getMethod("speak");
speak.invoke(object);
} catch (NoSuchMethodException e) {
System.err.println(object + "没有 speak 方法");
}
//通过反射获取 sit方法
try {
Method sit = aClass.getMethod("sit");
sit.invoke(object);
} catch (NoSuchMethodException e) {
System.err.println(object + "没有 sit 方法");
}
} catch (Exception e) {
throw new RuntimeException(object.toString(), e);
}
}
}
class LatentReflection{
public static void main(String[] args) {
CommunicateReflectively.performs(new SmartDog());
CommunicateReflectively.performs(new Robot());
CommunicateReflectively.performs(new Mime());
}
}
//运行结果为
Woof!
Sitting
Click
Clank
Mime没有 speak 方法
Mime sit()
将一个方法应用于序列
public class Apply {
static > void apply(S s, Method method, Object... args) {
try {
for (T t : s) {
method.invoke(t, args);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
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 extends T> type,int size){
try{
for (int i = 0; i < size; i++) {
//假设默认构造函数
add(type.newInstance());
}
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
class ApplyTest{
public static void main(String[] args) throws NoSuchMethodException {
List shapes=new ArrayList<>();
for (int i = 0; i < 10; i++) {
shapes.add(new Shape());
}
// 需要注意的通过反射获取方法必须是public
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);
FilledList filledList=new FilledList<>(Shape.class,10);
Apply.apply(filledList,Shape.class.getMethod("rotate"));
FilledList squares1=new FilledList<>(Square.class,10);
Apply.apply(squares1,Square.class.getMethod("rotate"));
SimpleQueue simpleQueue=new SimpleQueue();
for (int i = 0; i < 5; i++) {
simpleQueue.add(new Shape());
simpleQueue.add(new Square());
}
Apply.apply(simpleQueue,Shape.class.getMethod("rotate"));
}
}
class SimpleQueue implements Iterable{
private LinkedList storage=new LinkedList<>();
void add(T t){
storage.add(t);
}
T get(){
return storage.poll();
}
@Override
public Iterator iterator() {
return storage.iterator();
}
}
当你并未碰巧拥有正确的接口时
public class Fill {
static void fill(Collection collection, Class extends T> classToken, int size) {
for (int i = 0; i < size; i++) {
try {
collection.add(classToken.newInstance());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
class Contract {
static long counter = 0;
final long id =counter++;
@Override
public String toString() {
return getClass().getName()+" "+id;
}
}
class TitleTransfer extends Contract{
public static void main(String[] args) {
List list=new ArrayList<>();
Fill.fill(list,Contract.class,3);
Fill.fill(list,TitleTransfer.class,2);
for (Contract contract:list) {
System.out.println(contract);
}
}
}
//运行结果为
generic.Contract 0
generic.Contract 1
generic.Contract 2
generic.TitleTransfer 3
generic.TitleTransfer 4
用适配器仿真潜在类型机制
interface Addable {
void add(T t);
}
public class Fill2 {
public static void fill(Addable addable,Class extends T> classToken,int size){
for (int i = 0; i < size; i++) {
try {
addable.add(classToken.newInstance());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
//generator version
public static void fill(Addable addable,Generator generator,int size){
for (int i = 0; i < size; i++) {
addable.add(generator.next());
}
}
}
//要适应基本类型,您必须使用合成,使用组合使任何集合可添加
class AddableCollectionAdapter implements Addable{
private Collection collection;
public AddableCollectionAdapter(Collection collection) {
this.collection = collection;
}
@Override
public void add(T t) {
collection.add(t);
}
}
class Adapter{
public static Addable collectionAdapter(Collection collection){
return new AddableCollectionAdapter(collection);
}
}
//要适应特定类型,可以使用继承,使用继承使simpleQueue可添加
class AddableSimpleQueue extends SimpleQueue implements Addable{
@Override
public void add(T t) {
super.add(t);
}
}
class CoffeeDemo{}
class Fill2Test{
public static void main(String[] args) {
List coffees=new ArrayList<>();
Fill2.fill(new AddableCollectionAdapter<>(coffees),Coffee.class,3);
//辅助方法捕获类型
Fill2.fill(Adapter.collectionAdapter(coffees),Latte.class,3);
for (Coffee coffee:coffees) {
System.out.println(coffee);
}
System.out.println("--------------------");
//使用改编的课程
AddableSimpleQueue coffees1=new AddableSimpleQueue<>();
Fill2.fill(coffees1,Mocha.class,4);
Fill2.fill(coffees1,Latte.class,1);
for (Coffee coffee:coffees1) {
System.out.println(coffee);
}
}
}
//运行结果为
Coffee 0
Coffee 1
Coffee 2
Latte 3
Latte 4
Latte 5
--------------------
Mocha 6
Mocha 7
Mocha 8
Mocha 9
Latte 10
//接口部分
public interface Combiner {
T combine(T t,T y);
}
interface UnaryFuncation{
R function(T t);
}
interface Collector extends UnaryFuncation{
//提取采集参数结果
T result();
}
interface UnaryPredicate{
boolean test(T x);
}
2,实体类部分
public class Functional {
//在每个元素上调用合并器对象进行合并,运行结果最终返回
public static T reduce(Iterable iterable, Combiner combiner) {
Iterator iterator = iterable.iterator();
if (iterator.hasNext()) {
T result = iterator.next();
while (iterator.hasNext()) {
result = combiner.combine(result, iterator.next());
}
return result;
}
//如果iterable是空列表 或者 抛出异常
return null;
}
//取一个函数对象并在列表中的每个对象上调用它,忽略返回值,函数 object可以充当收集参数,因此最后返回
public static Collector forEach(Iterable it,Collector func){
for (T t:it) {
func.function(t);
}
return func;
}
//通过调用一个创建结果列表,列表中每个对象的功能对象
public static List transform(Iterable seq,UnaryFuncation func){
List list=new ArrayList<>();
for (T t:seq) {
list.add(func.function(t));
}
return list;
}
//将一元谓词应用于序列中的每个项目,并返回产生真实值的项目列表
public static List filter(Iterable seq,UnaryPredicate pred){
List result=new ArrayList<>();
for (T t:seq) {
if (pred.test(t)){
result.add(t);
}
}
return result;
}
//要使用上述通用方法,我们需要创建,功能对象以适应我们的特殊需求
public static class IntegerAddr implements Combiner{
@Override
public Integer combine(Integer integer, Integer y) {
return integer+y;
}
}
public static class IntegerSubtracter implements Combiner{
@Override
public Integer combine(Integer integer, Integer y) {
return integer-y;
}
}
public static class BigDecimalAddr implements Combiner{
@Override
public BigDecimal combine(BigDecimal bigDecimal, BigDecimal y) {
return bigDecimal.add(y);
}
}
public static class BigIntergerAdder implements Combiner{
@Override
public BigInteger combine(BigInteger bigInteger, BigInteger y) {
return bigInteger.add(y);
}
}
public static class AtomicLongAdder implements Combiner{
@Override
public AtomicLong combine(AtomicLong atomicLong, AtomicLong y) {
//不清楚这是否有意义
return new AtomicLong(atomicLong.addAndGet(y.get()));
}
}
//我们甚至可以用ulp制作UnaryFunction,最后单位
public static class BigDecimalulp implements UnaryFuncation{
@Override
public BigDecimal function(BigDecimal bigDecimal) {
return bigDecimal.ulp();
}
}
public static class GreaterThan> implements UnaryPredicate{
private T bound;
public GreaterThan(T bound) {
this.bound = bound;
}
@Override
public boolean test(T x) {
return x.compareTo(bound) > 0;
}
}
public static class MultiplyingIntegerCollector implements Collector{
private Integer val=1;
@Override
public Integer function(Integer integer) {
val *=val;
return val;
}
@Override
public Integer result() {
return val;
}
public static void main(String[] args) {
//泛型varargs和boxing一起工作
List lists= Arrays.asList(1,2,3,4,5,6,7);
Integer result=reduce(lists,new IntegerAddr());
System.out.println(result);
result=reduce(lists,new IntegerSubtracter());
System.out.println(result);
System.out.println(filter(lists,new GreaterThan<>(4)));
System.out.println(forEach(lists,new MultiplyingIntegerCollector()).result());
System.out.println(
forEach(filter(lists,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 BigDecimalAddr());
System.out.println(rbd);
System.out.println(filter(lbd,new GreaterThan<>(new BigDecimal(3))));
//使用bigInteger的原始生成功能
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);
List list=Arrays.asList(
new AtomicLong(11),
new AtomicLong(47),
new AtomicLong(74),
new AtomicLong(133)
);
AtomicLong atomicLong = reduce(list, new AtomicLongAdder());
System.out.println(atomicLong);
System.out.println(transform(lbd,new BigDecimalulp()));
}
}
}
3运行结果为
28
-26
[5, 6, 7]
1
1
11.000000
[3.300000, 4.400000]
[11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
265
[0.000001, 0.000001, 0.000001, 0.000001]
4 总结