为什么String在Java中是不可变的或最终的 [英] Why String is immutable or final in Java

查看:238
本文介绍了为什么String在Java中是不可变的或最终的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我被告知这是Java中重要的字符串访谈问题,首先讨论什么是字符串,字符串在java中与C或C ++中的不同之处,然后你被问及不可变对象,你就是问了一个主要问题:为什么String在Java中是不可变的或最终的。

As i was told this is important String Interview question in Java, which starts with discussion of " What is String ", how String is different in java than in C or C++ and then you are asked about immutable objects and you're asked the main question: " Why String is immutable or final in Java ".

你能分享你的想法吗?

Can you share your Ideas ?

提前致谢。

推荐答案

主要针对安全原因。字符串用作网络连接中的参数,数据库URL等。如果它是可变的,它很容易受到攻击

It is mainly for security reasons. String is used as parameter in network connection, database url etc. It can be easily attacked if it is mutable

字符串的不可变性解决了一些同步问题,它使字符串线程安全

Immutability of String solves some synchronization issues, it makes the String thread safe

到支持 StringPool 设施

缓存 哈希码 String

支持类加载机制,其中 String 用作参数。字符串是可变的导致错误的类被加载

To support class loading mechanism in which String is used as arguments. String being mutable results in wrong class being loaded

这篇关于为什么String在Java中是不可变的或最终的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆