Char vs String in Java? [英] Char vs String in Java?

查看:191
本文介绍了Char vs String in Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今年正在学习Java作为AP计算机科学课程的一部分,虽然我在阅读有关Char和字符串我不明白为什么会麻烦使用Char,只能存储一个字符,而不仅仅是使用字符串,并能够存储多得多。

I am learning Java this year as part of the AP Computer Science curriculum, and while I was reading about "Char" and "String" I could not understand why one would bother to use "Char" and only be able to store one character rather than just use "String" and be able to store much more than that. In short what's the point of "char" if it can only store a single character?

推荐答案

人们提到了内存方面的问题,是有效的,但我不认为这是一个非常重要的原因99%的时间。一个重要的原因是,Java编译器会告诉你是否犯了一个错误,所以你不必自己弄明白。

People are mentioning memory concerns, which are valid, but I don't think that's a very important reason 99% of the time. An important reason is that the Java compiler will tell you if you make a mistake so you don't have to figure it out on your own.

例如,如果变量只需要1个字符,可以使用 char 现在没有人可以把任何东西在那里,而不是一个错误。如果你使用 String ,字符串中可能有两个字符,即使你打算永远不可能。事实上,字符串中可能有0个字符,这也是同样糟糕的。此外,使用 String 的所有代码都必须说获取字符串的第一个字符,它可以

For example, if you only want 1 character for a variable, you can use a char to store the value and now nobody can put anything else in there without it being an error. If you used a String instead, there could be two characters in the String even though you intended that to never be possible. In fact, there could be 0 characters in the String which would be just as bad. Also, all your code that uses the String will have to say "get the first character of the String" where it could simply say, "give me the character".

一个比喻(对你来说可能没有意义,不幸的是),为什么我会说一个有一个名称,当我可以说一个 c> Names ?同样的原因也适用。如果你只想让 Person 有一个 Name ,那么给他一个 Name 增加了很多维护开销。

An analogy (which may not make sense to you yet, unfortunately) would be, "Why would I say a Person has a Name when I could say a Person has a List of Names?" The same reasons apply. If you only want a Person to have one Name, then giving him a list of Names adds a lot maintenance overhead.

这篇关于Char vs String in Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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