File tree Expand file tree Collapse file tree
java-base-demo/src/main/java/com/jay/innerClass Expand file tree Collapse file tree Original file line number Diff line number Diff line change 33import java .awt .*;
44import java .awt .event .ActionEvent ;
55import java .awt .event .ActionListener ;
6+ import java .util .Arrays ;
67import java .util .Date ;
78
89/**
@@ -47,10 +48,18 @@ public void actionPerformed(ActionEvent e) {
4748
4849
4950 public void start2 () {
50- int counter = 0 ;
51+ int [] counter = new int [ 1 ] ;
5152 Date [] dates = new Date [100 ];
5253 for (int i = 0 ; i < dates .length ; i ++) {
53-
54+ dates [i ] = new Date (){
55+ @ Override
56+ public int compareTo (Date other ) {
57+ counter [0 ]++; //ERROR
58+ return super .compareTo (other );
59+ }
60+ };
61+ Arrays .sort (dates );
62+ System .out .println (counter +"comparisons" );
5463 }
5564 }
5665 }
Original file line number Diff line number Diff line change @@ -109,5 +109,45 @@ class TalkingClock {
109109
110110假设想更新在一个封闭作用域内的计数器。这里想要统计一下在排序过程中调用
111111` compareTo ` 方法的次数
112+ ```
113+ public void start2() {
114+ int counter = 0;
115+ Date[] dates = new Date[100];
116+ for (int i = 0; i < dates.length; i++) {
117+ dates[i] = new Date(){
118+ public int compareTo(Date other) {
119+ counter++; //ERROR
120+ return super.compareTo(other);
121+ }
122+ };
123+ Arrays.sort(dates);
124+ System.out.println(counter+"comparisons");
125+ }
126+ }
127+
128+ ```
129+ 可以替代的方案是:
130+ ```
131+ public void start2() {
132+ int[] counter = new int[1];
133+ Date[] dates = new Date[100];
134+ for (int i = 0; i < dates.length; i++) {
135+ dates[i] = new Date(){
136+ @Override
137+ public int compareTo(Date other) {
138+ counter[0]++; //ERROR
139+ return super.compareTo(other);
140+ }
141+ };
142+ Arrays.sort(dates);
143+ System.out.println(counter+"comparisons");
144+ }
145+ }
146+ ```
147+ ### 匿名内部类
148+ 只创建了一个类的一个对象。
149+ 由于构造器的名字必须与类名相同,而匿名内部类没有类名。所以,匿名类不能有构造器。取而代之的是,将构造器参数
150+ 传递给超类构造器。尤其是在内部类实现接口的时候,不能有任何构造参数。
151+
112152
113153
You can’t perform that action at this time.
0 commit comments