Java-按值传递

Java-按值传递,java,Java,我试着用Integer做些什么,结果把我吓坏了 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++;

我试着用Integer做些什么,结果把我吓坏了

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

我想了解为什么会发生这种情况?

count++只是一种方便

count = Integer.valueOf(count.intValue()+1)
在此操作之后,returnBool中的局部变量计数引用另一个对象,main方法中的局部变量始终指向初始对象。你还没有达到通过参考的目的


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

Java通过值而不是引用传递类Integer。如果您想通过引用传递它,您需要另一个类,如apache commons库中的org.apache.commons.lang.mutable.MutableInt,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);
  }
}

Java始终是不可变的,整数对象是不可变的。每当你认为你可能要改变一个整数的值时,你真正要做的就是得到一个新的值。你应该只返回计数。Java不支持按引用传递,从来没有。你可以模拟它,但它很难看,我建议你阅读上一个问题中给出的答案,它向你展示了你应该如何做。很抱歉,我把你弄糊涂了,因为这个人问了同样的作业。是的,我知道,java是按值传递的,不知何故,我在脑海中输入了按值传递的引用。@Marko已经解释了我在寻找什么我认为tere在Java中不是通过引用传递的!您认为正确:没有。解决方案是创建一个包含整数的类,并将该类传递给该方法。在方法中,重写/更新类内的整数引用。退出该方法时,该类将保存新的Integer对象。另一种解决方案是使用全局变量如果您有问题,并且认为我知道,我将使用全局变量。现在有两个问题。实际上它通过值传递引用。引用在方法内部得到更新,但类外部的初始引用仍然引用旧对象。好的,谢谢您提供的信息。我只知道Java Integer类是不可变的;