有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java这个程序的流程是什么?请启发我的知识

调用obj1时会发生什么。test2(obj2)此方法中应用了哪些值?如果我们交换这些值,那么之前的值和应用的值是什么?请启发我的知识

package app4;

public class T 
{
  int i;
  static void test1(T t1, T t2)
  {
    int x = t1.i;
    t1.i = t2.i;
    t2.i = x;
  }
  void test2(T t1)
  {
    int x = t1.i;
    t1.i = this.i;
    this.i = x;
  }
  public static void main(String[] args) 
  {
    T obj1 = new T(), obj2 = new T();
    obj1.i = 1;
    obj2.i = 2;
    test1(obj1, obj2);
    System.out.println(obj1.i + "," + obj2.i);
    obj1.test2(obj2);
    System.out.println(obj1.i + "," + obj2.i);
  }
}

共 (1) 个答案

  1. # 1 楼答案

    这两种方法都在对象值之间进行交换。唯一的区别是,一种方法使用两个参数,另一种只使用一个参数。为了更好地理解,你可以跟随评论

    public class T 
    {
      int i;
      static void test1(T t1, T t2) // t1 = 1, t2 = 2
      {
        int x = t1.i;
        t1.i = t2.i;
        t2.i = x;
      }
      void test2(T t1) // t1 = 1
      {
        int x = t1.i;  
        t1.i = this.i; // 'this' is a keyword in java that is referring to the current object 
        this.i = x;    /* in our case the current object is obj1, and because the values have
                        * been swapped in the first method, this.i = 2 */
      }
      public static void main(String[] args) 
      {
        T obj1 = new T(), obj2 = new T();
        obj1.i = 1;
        obj2.i = 2;
        test1(obj1, obj2); // after returning from this method: obj1 = 2, obj2 = 1
        System.out.println(obj1.i + "," + obj2.i);
        obj1.test2(obj2); // after returning from this method: obj1 = 1, obj2 = 2
        System.out.println(obj1.i + "," + obj2.i);
      }
    }