A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© kmlitheima 中级黑马   /  2015-6-3 22:02  /  614 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

public class Example{        
        String str=new String("good");
        char[]ch={'a','b','c'};
        public static void main(String args[]){
           Example ex=new Example();
           ex.change(ex.str,ex.ch);
           System.out.print(ex.str+" and ");
      System.out.println(ex.ch);
          }
       
        public void change(String str,char[] ch){
            str="test ok";
            ch[0] = 'g' ;
          }
        }

1 个回复

倒序浏览
因为String类型的变量指向的是内存中的一个地址值,你虽然在change 方法中改变了引用指向,却没有把这种改变返回给原来的变量,数组虽然也是指向内存中的一个地址,但是针对ch[0]却是指向的内存中的数值,改变了值就会直接返回到原来的结果中
  1. public class Example{         
  2.         String str=new String("good");
  3.         char[]ch={'a','b','c'};
  4.         public static void main(String args[]){
  5.            Example ex=new Example();
  6.            //将通过change方法改变的str引用的结果返回给原来的变量
  7.            ex.str= ex.change(ex.str,ex.ch);
  8.            System.out.println(ex.str+" and ");
  9.            System.out.println(ex.ch);
  10.         }
  11.         
  12.         public String change(String str,char[] ch){
  13.                  return str="test ok"; //改变引用指向
  14.                  //ch[0]='g';
  15.            
  16.         }
  17.    }
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马