自定义的Key类需要重载equals, hashCode函数。。
package com.albert.test;
import java.util.Vector;
import java.util.HashMap;
/**
* @author tough_guy
*
*/
//对于自定义的key, 需要重载hashCode函数和equals函数
class IPSegment
{
long ip_s;
long ip_e;
int p;
IPSegment Reset(long f1, long f2, int f3)
{
ip_s = f1;
ip_e = f2;
p = f3;
return this;
}
public boolean equals(Object so)
{
if(! (so instanceof IPSegment))
return false;
if(this.ip_s == ((IPSegment)so).ip_s && this.ip_e == ((IPSegment)so).ip_e && this.p == ((IPSegment)so).p)
return true;
else
return false;
}
public int hashCode()
{
return (int)(ip_s + ip_e + p);
}
}
public class TestString {
Vector vi = new Vector();
HashMap hii = new HashMap();
HashMap hss = new HashMap();
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestString ts = new TestString();
ts.vi.add(new IPSegment().Reset(1, 2, 3));
ts.vi.add(new IPSegment().Reset(2, 2, 4));
ts.vi.add(new IPSegment().Reset(3, 2, 5));
ts.vi.add(new IPSegment().Reset(4, 2, 6));
System.out.println(ts.vi.size());
System.out.println(ts.vi.get(2).ip_s + "\t" + ts.vi.get(2).ip_e + "\t" + ts.vi.get(2).p);
ts.hii.put(new IPSegment().Reset(2,2,3), 4);
ts.hii.put(new IPSegment().Reset(2,3,3), 7);
ts.hii.put(new IPSegment().Reset(3,2,3), 9);
System.out.println(ts.hii.size());
System.out.println(ts.hii.toString());
System.out.println((Integer)ts.hii.get(new IPSegment().Reset(2,3,3)));
System.out.println((Integer)ts.hii.get(new IPSegment().Reset(3,2,3)));
ts.hss.put("1", "hello");
System.out.println((String)ts.hss.get("1"));
}
}