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中。

转载于:https://www.cnblogs.com/wumao/archive/2011/05/22/2052680.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值