关于java final,并非不可更改值

  • Post author:
  • Post category:java




对于final型的变量,一般情况下是在赋值后就不能改变值了。但是,对于数组,仍然能够修改元素值。例如:

int counter = 0;
Date[] dates = new Date[100];
for(int i = 0; i< dates; i++){
    dates[i] = new Date(){
             public int compareTo(Date other){
                       counter++;//ERROR
                       return super.compareTo(other);
             }
     }
}


上例中,counter++出错误的原因是:dates[i] = new Date(){…}创建了一个本地内部类(Local inner class),传递给该本地内部类的变量都要转换为final,这样的原因是new Date()只会在内存中临时存在,会被JVM删除,所以counter要为final型;



但是,如果像下面这样就可以修改counter的值了:

final int[] counter = new int[1];
for(int i=0; i<dates.length; i++){
  dates[i] = new Date(){
          public int compareTo(Date other){
                   counter[0]++;
                   return super.compareTo(other);
           }
  }
}


数组仍然被定义为final,仅仅意味着我们不能将其赋值为其它数组,我们可以修改数组元素的值。




版权声明:本文为yuetingzhuying原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。