public class a{
   public b bb[] = new b[3];   public class b{
      public void test(){
      index = 9;
        if (bb[0] == this) index = 0;
      
        if (bb[1] == this) index = 1;
      
        if (bb[2] == this) index = 2;
System.out.println(index);
      }
   }
   public a(){
     bb[0]=new b();
     bb[1]=new b();
     bb[2]=new b();   }
}
结果是index=0
我就不明白为什么bb[0]会等于this.我觉的应该每个类都是不同的地址呀

解决方案 »

  1.   

    我觉得结果应该是0,1,2;bb[0].test(); 0
    bb[1].test(); 1
    bb[2].test(); 2其实楼主并没有描述清楚你的程序如何运行,而且结果应该有三行结果吧
      

  2.   

    public class a{
       public b bb[] = new b[3];   public class b{
          public void test(){
          int index = 9;
            if (bb[0] == this) index = 0;
          
            if (bb[1] == this) index = 1;
          
            if (bb[2] == this) index = 2;
    System.out.println(bb[0]);
    System.out.println(bb[1]);
    System.out.println(bb[2]);
    System.out.println(this);
    System.out.println(index);
          }
       }
       public a(){
         bb[0]=new b();
         bb[1]=new b();
         bb[2]=new b();
         bb[0].test();
       }
       public static void main(String[] args){
        a ad = new a();   }
    }结果是:
    a$b@35ce36
    a$b@757aef
    a$b@d9f9c3
    a$b@35ce36
    0
    也就是说bb[0]和this的地址是一样的,不明白是什么原因
      

  3.   

    不懂 public b bb[] = new b[3]; 这句
      

  4.   

    你调用的是 bb[0].test();在test里面又是:
    public void test(){
          int index = 9;
            if (bb[0] == this) index = 0;
          
            if (bb[1] == this) index = 1;
          
            if (bb[2] == this) index = 2;
    System.out.println(bb[0]);
    System.out.println(bb[1]);
    System.out.println(bb[2]);
    System.out.println(this);
    System.out.println(index);
          }这个时候的this对象就是bb[0]了。你可以换成bb[1].test();那么输出的就是1了。
      

  5.   

    同意foxty答案。
    其实从test()代码来看,作用主要是判断当前是b类的哪个对象调用了test()方法;具体在这里就是三个数组元素。现在调用的是bb[0].test();当然 if (bb[0] == this) index = 0;
    条件为真。还有问题的关键就是this的意义,它是指调用该方法的当前对象。
      

  6.   

    那么this是代表class b 
    还是代表当前调用这个类的对像
      

  7.   

    你这里的class b就是你当前调用的这个类的对象。换另外一种说法,或许更清楚一些。jvm再调用对象方法的时候,默认第一个参数就是this,只是这个被应藏起来了,你是看不见的。所以b[0].test(); 其实可以看成是 b[0].test(b[0]);这里的参数就是test方法里面的this。