Java笔记(三)内部类,容器,泛型和类型安全的容器,迭代器

继续内部类

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类型访问。其可以双向移动。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

帅逼码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值