开发者

date = date + part vs. date.concat(part)

I've got a small Java program that I'm developing for a project, which pulls a user's inbox from a specified URI using JavaMail, and then begins processing the messages.

In Outlook, there's a function in the properties menu to set an expiry date for the message, which adds (for example):

Expiry-Date: Thu, 14 Jan 2010 17:00:00 -0000

To the message header.

Retrieving that from the email header is simple using the getHeader(String header) method from javax.mail.Message, and it returns a String[], in which happens to be the part after the colon, tokenised by spaces.

What I want to do is make this String[] into a single String, to later make into a Date. So setting up a simple foreach loop as follows:

String date = "";
for(String part : header){
  date.concat(开发者_运维技巧part);
}
System.out.println(date);

Now for some reason, this code returns an empty string, not entirely sure why, as this should be valid Java.

However, the following code does work, and I don't know why, as it seems illogical to me

String date = "";
for(String part : header){
   date = date + part;
}
System.out.println(date);

Which prints out the correct date. Can someone tell me if this is the correct way of doing this, and if not, what's going wrong with the concat(String append) method?

TIA,

JimiF


String is immutable. Its internals will never be changed from outside (leaving reflection aside). As per the API docs, the String#concat() returns a new String containing the concatenatred parts, but you're ignoring it. You need to get a handle of it and continue using it in the loop:

String date = "";
for(String part : header){
    date = date.concat(part);
}
System.out.println(date);

That said, your second example can also be shortened to:

String date = "";
for(String part : header){
    date += part;
}
System.out.println(date);

That in turn said, in real world you'd like to use a StringBuilder for this to save the memory, because constructing a new String in a loop isn't cheap if you do this too often:

StringBuilder date = new StringBuilder();
for(String part : header){
    date.append(part);
}
System.out.println(date.toString());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜