0

我正在尝试使用整数,输出让我感到害怕。

public class CountB
{

  public static boolean returnBool(String w, Integer count)
  {
     for (int i = 0; i < w.length(); i++)
     {
         if (w.charAt(i) == 'B' || w.charAt(i) == 'b')
        {
       count++;
        }
     }

    if (count > 0)
      return true;
    return false;
   }

  // write the static method “isThisB” here
  public static void main(String[] args)
  {
    //  Scanner keyboard = new Scanner(System.in);
   //   System.out.println("Enter a string: ");
   String w = "fgsfbhggbB";//keyboard.nextLine();
   Integer count = new Integer(0);
   System.out.println(returnBool(w, count));
   System.out.println("Number of B and b: " + count);
  }
}

现在,Integer作为 的包装类int,并count作为它的对象,当我count从 main 传递到 时returnBool,的值count变为 3,所以它返回true,因为 java 是按值传递的,count对象的值也应该在main方法中改变,但main count打印为 0。

我想了解为什么会这样?

4

3 回答 3

11

count++只是为了方便

count = Integer.valueOf(count.intValue()+1)

执行此操作后,您的局部变量count(in returnBool) 引用了另一个对象,并且您main方法中的局部变量一直指向初始对象。您还没有实现通过引用。

至于Java语义,有两个类似的概念很容易混淆:Java的对象引用(本质上是指针)的按值传递,和真正的按引用传递。您的示例强调了这种差异。

于 2013-11-08T09:38:19.087 回答
1

Java 通过值而不是通过引用传递类 Integer。org.apache.commons.lang.mutable.MutableInt如果你想通过引用传递它,你需要一个来自 Apache Commons 库的其他类

于 2013-11-08T09:39:23.390 回答
0

java中没有传递引用。方法参数按值传递,但该值可能是对对象的引用。如果传递的对象是可变的,则其上的更改将影响方法外部的对象,因为对象的输入和输出相同。整数对象是不可变的。您可以传递 int[1] 或 AtomicReference 或 AtomicInteger 或任何其他包含可变整数值的对象。

这是您适应 AtomicInteger 的代码

public class CountB
{

  public static boolean returnBool(String w, AtomicInteger count)
  {
     for (int i = 0; i < w.length(); i++)
     {
         if (w.charAt(i) == 'B' || w.charAt(i) == 'b')
        {
       count.incrementAndGet();
        }
     }

    if (count.intValue() > 0)
      return true;
    return false;
   }

  // write the static method “isThisB” here
  public static void main(String[] args)
  {
    //  Scanner keyboard = new Scanner(System.in);
   //   System.out.println("Enter a string: ");
   String w = "fgsfbhggbB";//keyboard.nextLine();
   AtomicInteger count = new AtomicInteger(0);
   System.out.println(returnBool(w, count));
   System.out.println("Number of B and b: " + count);
  }
}
于 2013-11-08T09:56:10.180 回答