2011.5.21

1、对于多态:

class C1{}

class C2 extends C1{}

class Test{

  void f1(C2 c){}

  void f2(C1 c){}

}

2、final关键字:

final用于声明类,表示此类不会被继承。

final用于声明方法,表示此方法可以被继承,但不可以被重写。

final用于声明成员变量,指声明常量,不可以被修改,但可以被继承。

final用于声明方法内变量,指声明此变量为常量,只可以初始化时赋值,不可以被修改。

3、对于泛型:

class C1{}

class C2 extends C1{}

  List<C1> list = new ArrayList<C2>();//error

  List<C1> list = new ArrayList<C1>();

  List<C2> listC2 = new ArrayList<C2>();

  list = listC2;//error

4、对于Set:

public class Main {

/**
*
@param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
    Set<C1> set = new HashSet<C1>();
          set.add(new Main().new C1());
          set.add(new Main().new C1());
          System.out.println(set);
       
          Set<String> set2 = new HashSet<String>();
          set2.add(new String("dd"));
          set2.add(new String("dd"));
          set2.add(new String("ee"));
          System.out.println(set2);
}
class C1 {
@Override
public int hashCode() {
return 1;
}
@Override
public boolean equals(Object c){
return true;
}
}

}
//console output
 [Main$C1@1]
[dd, ee]

//分析:
即重写hashCode()和equals()即,可对Set容器面添加的元素进行是否一样控制,就像String做的那样
class String{

、、、

public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString
= (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}

public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;

for (int i = 0; i < len; i++) {
h
= 31*h + val[off++];
}
hash
= h;
}
return h;
}
}

这是因为HashSet里面是用HashMap实现的,用一个HashMap对象来存储对象引用,把对象当作map的key添加,仅当新添加的对象和其他的对象不equals
且hashCode不相同时才会被添加到map中。
posted @ 2011-05-22 15:49  奋奋  阅读(201)  评论(0编辑  收藏  举报