Record a java reference passing problem

Lou Zi 2021-11-25 17:57:45
record java reference passing problem

Preface

I've been writing for the first two months PHP Went to the , I feel like I haven't written for a long time Java Code , Because I'm going to restructure the company's Java project , Also put Java pick up . In the process of writing code , There's one thing I didn't pay much attention to before , Almost stepped on , Just make a simple record through this article .

Java Value passing and reference passing

Java There are two main types of data in , Basic types and object types . Corresponding , There are also two types of variables : Basic types and reference types .

  • Basic types of variables hold the original values , That is, the value it represents is the value itself ;
  • Variables of reference type save reference values ," Reference value " The address to the memory space , Represents a reference to an object , Not the object itself , The object itself is stored in the location of the address represented by the reference value .

Value passing is limited to four categories and eight basic data types :

Get rid of these four categories and eight basic types , The others are objects , That is, reference types , Include : Class types , Interface types and arrays .

As for the memory allocation of the stack , I won't draw this , No example , There is a lot of information on the Internet .

reference

We ArrayList Take... For example “ reference ”, I defined the following two objects :

@Data
@NoArgsConstructor
public class DeptDTO {
    /**
     *  department ID dept_code
     */

    private String deptCode;

    /**
     *  Department name  dept_name
     */

    private String deptName;

    /**
     *  Department level  dept_level
     */

    private Integer deptLevel;
}

Sample code :

public static void main(String[] args) {
    DeptDTO dept1 = new DeptDTO();
    DeptDTO dept2 = new DeptDTO();

    dept1.setDeptCode("111");;
    dept2.setDeptCode("222");;

    List<DeptDTO> deptList = new ArrayList<>();
    deptList.add(dept1);
    deptList.add(dept2);

    for (DeptDTO deptRecord : deptList) {
        System.out.println("Print deptCode:" + deptRecord.getDeptCode());
    }

    //  Get the elements inside , It's actually a reference to get , Modify the element value , It will affect personList Value
    DeptDTO dept = deptList.get(0);
    dept.setDeptCode("333");

//        //  Modify the value , It will directly affect deptList Value , prove deptList.add() What is stored is the reference of the object
//        dept.setDeptCode("444");

    for (DeptDTO deptRecord : deptList) {
        System.out.println("Print deptCode:" + deptRecord.getDeptCode());
    }
}

//  Output :
// Print deptCode:111
// Print deptCode:222
// Print deptCode:333
// Print deptCode:222

We found that , obtain deptList The value of the inside , And then modify it , It will directly affect deptList The value of the inside , Because we got deptList The reference of the value inside . Maybe you think this is very simple , But writing habits Go and PHP Classmate , There will be some discomfort , such as PHP Get the data of the array , It's worth passing on , Not by reference , If you need to modify the data inside , Need to pass through deptList The corresponding index value can be modified directly .

Let's let go of the notes above :

//  Modify the value , It will directly affect deptList Value , prove deptList.add() What is stored is the reference of the object 
dept1.setDeptCode("444");

//  Output :
// Print deptCode:111
// Print deptCode:222
// Print deptCode:444
// Print deptCode:222

You can find dept、dept1 and deptList.get(0), Always point to the same address area , Let's simply verify , Add the code at the end :

System.out.println(System.identityHashCode(dept));
System.out.println(System.identityHashCode(dept1));
System.out.println(System.identityHashCode(deptList.get(0)));
//  Output :
// 1612799726
// 1612799726
// 1612799726

Problem introduction

In fact, my problem is mainly to use ArrayList and HashMap when , Encountered the problem of reference passing , Let's add another object :

@Data
public class DeptCalcuateDTO  extends DeptDTO {
    /**
     *  Calculate the data
     */

    private Integer calculateNumber;
}

In fact, the function I want is very simple , There is one List< DeptDTO > A, Now I need to bring A The data in is converted to DeptTreeDTO B, I wrote the following code :

DeptCalcuateDTO deptCalcuateDTO = (DeptCalcuateDTO) dept1;
deptCalcuateDTO.setDeptCode("333");

If the above grammar holds , Because it's passed by reference , So modify deptCalcuateDTO, Will affect A Data in , however A It's basic data , It is not allowed to modify , This goes against my original intention .

In fact, I found out later that I thought too much , Because I write Deom Use case, only to find that the above cast doesn't work , Because it throws ClassCastException() abnormal , however C++ This type of cast is supported .

solve the problem

It's actually a copy problem , I can just put A The data in is assigned to B, But the actual situation is that there are too many attributes , I don't want to switch every time , I borrowed a tool library , It feels good to use , Just record it .

Bring in the package first :

<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-processor</artifactId>
    <version>1.2.0.Final</version>
</dependency>

Add entity translator :

@Mapper(componentModel = "spring")
public interface AppDeptConverter {
    AppDeptConverter INSTANCE = Mappers.getMapper(AppDeptConverter.class);

    DeptCalcuateDTO toDeptCalcuate(DeptDTO deptDTO);
}

The test case :

public static void main(String[] args) {
    DeptDTO dept1 = new DeptDTO();
    DeptDTO dept2 = new DeptDTO();
    dept1.setDeptCode("111");
    dept2.setDeptCode("222");

    List<DeptDTO> deptList = new ArrayList<>();
    deptList.add(dept1);
    deptList.add(dept2);

    DeptCalcuateDTO deptCalcuateDTO =  AppDeptConverter.INSTANCE.toDeptCalcuate(dept1);
    deptCalcuateDTO.setDeptCode("333");

    for (DeptDTO deptRecord : deptList) {
        System.out.println("Print deptCode:" + deptRecord.deptCode);
    }
}
//  Output :
// Print deptCode:111
// Print deptCode:222

In fact, what this tool does is very simple , Generate a DeptCalcuateDTO object , And then A The values of are assigned to B, For detailed usage, please refer to :https://mapstruct.org/

Welcome to like it more , More articles , Please follow the WeChat public account “ Louzi's way to advancement ”, Focus , Neverlost ~~

版权声明
本文为[Lou Zi]所创,转载请带上原文链接,感谢
https://javamana.com/2021/11/20211109094851829W.html

  1. 数据结构实验八 领会图的两种主要储存结构和图的基本运算算法设计
  2. Hibernate数据校验简介
  3. Il a dépensé 270 000 yuans pour soulever Xiaopeng p7 et a parcouru 3 627 km. Le propriétaire du véhicule a partagé 6 avantages et inconvénients.
  4. 阿里蚂蚁花呗团队面试题:spring+分布式+jvm+session+redis
  5. 【Java入门100例】14.字符串排序——compareTo()
  6. 【Java入门100例】13.修改文件扩展名——字符串替换
  7. Leetcode 79. Word Search [C + + / java detailed problem]
  8. Introduction à la vérification des données hibernantes
  9. Expérience de la structure des données
  10. Spring cloud gateway practice 2: more routing configuration methods
  11. Java network programming - summary overview
  12. 基于语法树的 Java 代码自动化插桩
  13. 云原生 Spring Boot 应用配置 Prometheus + Grafana 监控(保姆级)
  14. Spring cloud gateway practice 2: more routing configuration methods
  15. Jenkins file one line of code to deploy. Net program to k8s
  16. Java network programming - summary overview
  17. Cloud Native Spring Boot application configuration Prometheus + grafana Monitoring (baby - sitter)
  18. Insertion automatique de code Java basée sur l'Arbre syntaxique
  19. Le SUV phare de Xiaopeng, Xiaopeng G9, a fait ses débuts au salon de l'automobile et s'est tenu en position C dans la nouvelle force?
  20. Docker 从入门到实践系列四 - Docker 容器编排利器 Docker Compose
  21. 6年老猿带你掌握Spring Boot实现定时任务的动态增删启停
  22. disruptor笔记之六:常见场景,java教程从入门到精通pdf百度云
  23. Pourquoi InnoDB n'utilise - t - il pas un cache LRU naïf?
  24. Java Reflection (2): quelques opérations de base de reflection
  25. 6年老猿帶你掌握Spring Boot實現定時任務的動態增删啟停
  26. Les singes âgés vous permettent de maîtriser le démarrage et l'arrêt dynamiques des tâches programmées par Spring boot
  27. Docker From Beginning to Practice Series IV - docker Container chorégraphe Clean docker Composition
  28. 编写 java 程序,为家用电脑 ipv6 自动更新 goddy dns 记录(ddns)
  29. java jvm-old gc耗时几十s,导致系统告警
  30. Disruptor note 6: scénario commun, tutoriel Java de l'introduction à la maîtrise du PDF Baidu Cloud
  31. 编写Java程序启动脚本最佳实践
  32. How to get the correct Linux user's documents, music videos and other directories?
  33. Java JVM Old GC prend des dizaines de s, ce qui provoque une alarme système
  34. Écrivez un programme Java pour mettre à jour automatiquement les enregistrements DNS goddy (ddns) pour l'ordinateur domestique IPv6
  35. 編寫Java程序啟動脚本最佳實踐
  36. Meilleures pratiques pour écrire des scripts de démarrage de programmes Java
  37. Notes sur springcloud Eureka
  38. Ajout, suppression et modification simples de mybatis
  39. MySQL Learning - Logging System Redo log and Bin log
  40. Springboot Common comments | @ configuration
  41. Mécanisme d'expiration du cache redis et d'élimination de la mémoire
  42. Analyse concise du code source redis 01 - configuration de l'environnement
  43. Java - carte mémoire de l'objet
  44. Redis source Concise Analysis 02 - SDS String
  45. Why did docker lose to kubernetes? Docker employee readme!
  46. Spring cloud gateway practice 2: more routing configuration methods
  47. Principe de mise en œuvre ultime du mécanisme de concurrence Java sous - jacent
  48. [démarrer avec Java 100 exemples] 13. Modifier l’extension de fichier - remplacement de chaîne
  49. Java期末作业——王者荣耀的洛克王国版游戏
  50. Elasticsearch聚合学习之五:排序结果不准的问题分析,阿里巴巴java性能调优实战
  51. Java期末作業——王者榮耀的洛克王國版遊戲
  52. Java final work - King's Glory Rock Kingdom Game
  53. 【网络编程】TCP 网络应用程序开发
  54. 【网络编程入门】什么是 IP、端口、TCP、Socket?
  55. 【網絡編程入門】什麼是 IP、端口、TCP、Socket?
  56. [Introduction à la programmation réseau] qu'est - ce que IP, port, TCP et socket?
  57. [programmation réseau] développement d'applications réseau TCP
  58. [Java Basics] comprendre les génériques
  59. Dix outils open source que les architectes de logiciels Java devraient maîtriser!!
  60. java架构之路(多线程)synchronized详解以及锁的膨胀升级过程,mysql数据库实用教程pdf