类的构造器也可以实现重载
类的继承体系结构
自动的拆装箱
写程序要考虑向后的兼容性(新特性不能滥用)
链表的实现 (用链表实现堆栈或队列都很方便)
查看jdk LinkedList源码(该实现为双向循环链表)万老师讲的是单向非循环链表:
该类内部使用了一个静态内部类Entry ,相当与今晚上课时讲的Node类
private static class Entry<E> {
E element;
Entry<E> next;
Entry<E> previous;
Entry(E element, Entry<E> next, Entry<E> previous) {
this.element = element;
this.next = next;
this.previous = previous;
}
}
也使用了头结点:
private transient Entry<E> header = new Entry<E>(null, null, null);
private transient int size = 0;
/**
* Constructs an empty list.
*/
public LinkedList() {
header.next = header.previous = header;
}
该实现是循环链表 ,从以下代码可知:
public E getLast() {
if (size==0)
throw new NoSuchElementException();
return header.previous.element;//返回头结点前面的元素即尾节点
}
问题一:如何判断一个链表上存在环?
方法1:
用两个临时变量,步伐不一致,进行遍历列表,如果存在环,则则两个变量总会在某一时刻指向同一节点。
问题二:如何找到环的起点。
有点烦,用数学可以推出来,满足一定的关系。也是相差n圈的问题。
快速排序法很重要啊。
static关键字
static关键字用来修饰变量,方法和内部类,称这些变量,方法和内部类为静态变量,静态方法和静态内部类
static关键字声明一个属性或方法是和类相关的,而不是和类的某个特定的实例相关,因此,这类属性或方法也称为“类属性”或“类方法”
如果访问控制权限允许,可不必创建该类对象而直接使用类名加“.”调用
static不可用于修饰构造器
设计模式:
单例设计模式
1,将构造器设为私有,向外提供一个获取单一实例的借口。
运用double check 技术,在多线程环境下保证生成唯一的实例
private Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null){
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
2,静态初始化实例,同时将构造器设为私有,提供返回该实例的借口。
public static Singleton instance = new Singleton();
看到以下写法,不知静态内部类的用意何在?
public class Singleton {
static class SingletonHolder {
static Singleton instance = new Singleton();
}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
}