Java中的字符与字符串?

2022-01-12 00:00:00 string char java

今年我正在学习 Java 作为 AP 计算机科学课程的一部分,当我阅读Char"和String"时,我不明白为什么有人会费心使用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".

一个类比(不幸的是,这对你来说可能还没有意义)是,为什么我会说一个 Person 有一个 Name 而我可以说 PersonNames 列表?"同样的原因也适用.如果您只希望 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.

相关文章