起因: 手写hashMap 时发现通过this调用构造器时报错
public class MyHashMap<K, V> implements MyMap<K, V>
{
private int defaultLenth = 1 << 4;
private float defaultAddSizeFactor = 0.75f;
public MyHashMap()
{
this(defaultLenth, defaultAddSizeFactor);//这里报错
}
public MyHashMap(int defaultLenth, float defaultAddSizeFactor)
{
if (defaultLenth < 0)
{
throw new IllegalArgumentException("数组长度大于0:" + defaultLenth);
}
if (defaultAddSizeFactor <= 0 || Double.isNaN(defaultAddSizeFactor))
{
throw new IllegalArgumentException("扩容因子应该大于0:" + defaultAddSizeFactor);
}
this.defaultLenth = defaultLenth;
this.defaultAddSizeFactor = defaultAddSizeFactor;
}
}
解决办法:将defaultLenth 和defaultAddSizeFactor改为static 的
原因分析:
1:如果不加static ,这两个属性是成员属性
2:成员属性的值 应该是 创建对象并初始化对象中的数据域时才会确定,但此时对象还未创建,属性值不确定,所以不能使用
3:加上static,这两个属性就是类属性,可以通过类获取,在创建对象前已经确定,可以使用
附: 对象初始化顺序
public class Test2
{
private static int a = total(1);
private final int b = get(a);
private final int c = count(a);
private final Obj obj = new Obj(c);
static
{
System.out.println("STATIC test2");
}
public Test2()
{
this(a);
System.out.println("Constructor test2");
}
public static int total(int i)
{
System.out.println("STATIC TOTAL i = " + i);
return i;
}
public Test2(int i)
{
System.out.println("Constructor test2 i= " + i);
}
public int get(int i)
{
System.out.println("get i=" + i);
return i;
}
public int count(int i)
{
i *= 10;
System.out.println("count i = " + i);
return i;
}
public static void main(String[] args)
{
new SubTest();
}
}
class SubTest extends Test2
{
private static int a = total(2);
private final int b = get(a);
private final int c = count(b);
private final Obj2 obj2 = new Obj2(c);
static
{
System.out.println("STATIC SubTest");
}
public SubTest()
{
this(a);
System.out.println("Constructor SubTest");
}
public SubTest(int i)
{
super(i);
System.out.println("Constructor SubTest i=" + i);
}
}
class Obj
{
static
{
System.out.println("STATIC Obj");
}
public Obj(int i)
{
System.out.println("Constructor Obj i=" + i);
}
}
class Obj2
{
static
{
System.out.println("STATIC Obj2");
}
public Obj2(int i)
{
System.out.println("Constructor Obj2 i=" + i);
}
}
输出结果:
STATIC TOTAL i = 1
STATIC test2
STATIC TOTAL i = 2
STATIC SubTest
get i=1
count i = 10
STATIC Obj
Constructor Obj i=10
Constructor test2 i= 2
get i=2
count i = 20
STATIC Obj2
Constructor Obj2 i=20
Constructor SubTest i=2
Constructor SubTest