欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Java中的按值传递和按引用传递的代码详解

时间:2021-03-07 10:32:27|栏目:JAVA代码|点击:

先使用int实验:

public class TTEST { 
  private static  List<UserEntity> mList = new LinkedList<UserEntity>();  
  public static void main(String[] args) { 
    int a = 0; 
    changeA(a); 
    System.out.println("a = "+a); 
  } 
   
  public static void changeA(int a){ 
    a = 1; 
  } 
}

输出:a = 0

这说明对于int值是按值传递。其他几个基本类型也是如此。

再使用自己定义的类UserEntity来实验:

public class UserEntity { 
  private String name; 
  public String getName() { 
    return name; 
  } 
  public void setName(String name) { 
    this.name = name; 
  } 
} 

public class TTEST { 
  public static void main(String[] args) { 
    UserEntity userEntity = new UserEntity(); 
    userEntity.setName("猿猴"); 
    changeName(userEntity); 
    System.out.println("name = "+userEntity.getName()); 
  } 
  public static void changeName(UserEntity userEntity){ 
    userEntity.setName("忽必烈"); 
  } 
} 

输出:name = 忽必烈

我们再来使用一个linkedList<Object>来实验:

import java.util.LinkedList; 
import java.util.List; 
public class TTEST { 
   private static List<UserEntity> mList = new LinkedList<UserEntity>();  
  public static void main(String[] args) { 
    UserEntity userEntity = new UserEntity(); 
    userEntity.setName("石头"); 
    addUser(userEntity); 
    System.out.println("name = "+userEntity.getName()); 
  } 
  public static void addUser(UserEntity userEntity){ 
    mList.add(userEntity); 
    mList.get(0).setName("猿猴"); 
  } 
} 

输出:name= 猿猴

这说明在使用我们自己定义的类时,是按引用传递的。

接着,再来使用String实验:

public class TTEST { 
  public static void main(String[] args) { 
    String str= "开始的"; 
    changeStr(str); 
    System.out.println("str = "+str); 
  } 
  public static void changeStr(String str){ 
    str = "改变的"; 
  } 
} 

输出:str = 开始的

用Integer做实验也会发现没有改变。

说明我们按照java内置的对象也是值传递。因此我们可以做如下总结:

只要我们自己定义的类创建的对象,都是引用传递,系统内置的基本类型和对象都是指传递。

总结

上一篇:Spring MVC前后端的数据传输的实现方法

栏    目:JAVA代码

下一篇:SpringMVC实现controller中获取session的实例代码

本文标题:Java中的按值传递和按引用传递的代码详解

本文地址:http://www.codeinn.net/misctech/76158.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有