继续内部类
package java_learn;
class call1 implements incrementable{
private int i;
@Override
public void increment() {
// TODO Auto-generated method stub
i++;
System.out.println(i);
//System.out.println("");
}
}
class MyIncrement{
public void increment() {
System.out.println("myincrement");
}
static void f(MyIncrement mi) {
mi.increment();
}
}
class call2 extends MyIncrement{
private int i=0;
public void increment() {
super.increment();
i++;
System.out.println(i);
}
private class Closure implements incrementable{
int i;
public void increment() {
out();
System.out.println(11);
call2.this.increment();
}
private void out() {
System.out.println(i++);
}
}
incrementable getcallbackreference() {
return new Closure();
}
}
class Caller{
private incrementable callbackreference;
Caller(incrementable s){
callbackreference=s;
}
void go() {
callbackreference.increment();
}
}
public class inner_good {
public static void main(String args[]) {
call1 c1=new call1();
call2 c2=new call2();
MyIncrement.f(c2); //输出myincrement 1
Caller caller1=new Caller(c1);
Caller caller2=new Caller(c2.getcallbackreference());
caller1.go();//输出1
caller1.go();//输出2
caller2.go();//输出myincrement 2
caller2.go();//输出myincrement 3
incrementable s=c2.getcallbackreference();
s.increment();//此处out输出i的值为0,表明是两个Clousre对象。但对同一个MyIncrement操作(都通过c2创建)。
}
}
myincrement
1
1
2
0
11
myincrement
2
1
11
myincrement
3
0
11
myincrement
4
进一步展示接口与内部类之间的区别。call1是接口简单实现方式。call2继承自MyIncrement,其已经有了一个increment方法,且与接口期望的increment方法完全不相关。所以就不能为了实现incrementable接口去覆盖increment方法,于是使用内部类。
内部类closure实现了接口,提供返回call2的钩子(call2.this.increment();)无论谁获得此incrementable调用,只能调用increment()
caller构造器需要接口的引用作为参数,在某个时候,caller对象可以回调call1,2类。
回调价值在于其灵活性,运行时动态决定调用什么方法。
容器
泛型和类型安全的容器
使用泛型,可以在编译器防止将错误类型的对象放到容器中。
向上转型也可以作用于泛型
https://blog.csdn.net/qq_40298054/article/details/84751056
map:map.put(key,value)将增加一个值,并将它与某个值联系起来。map.get(key)产生与这个值相关联的值。map会自动的调整尺寸。
迭代器
导入:要使用容器必须对确切容器类型编程。如果原本对List编码,后来想用于set。如何做到不重写代码就可应用于不同类型容器呢?
迭代器是一个对象,他的工作是遍历并选择序列中的对象,客户端程序员不需要知道序列底层结构。
display()方法不包含任何遍历序列类型信息,其能够将遍历序列操作与底层序列结构分离。
迭代器统一了对容器的访问方式
ListIterator是Iterator子类型,只用于List类型访问。其可以双向移动。