java基础 — String和MessageFormat的format方法

本文介绍了Java中String.format和MessageFormat.format的区别与性能,重点分析了两者在异常情况下的表现及实现原理。String.format依赖正则表达式,而MessageFormat.format采用预分析定位值,性能更优。此外,文章提供了详细的源码分析。
摘要由CSDN通过智能技术生成

String与MessageFormat的说明

一、两者的使用场景

String.Format:用于布局调整和对齐,用于数字、字符串和日期/时间数据的通用格式,以及特定于地区的输出。

MessageFormat.Format:以与语言无关的方式生成连接的消息。

二、两者的性能比较

MeesageFormat由于是一个在先分析的指定位置插入相应的值,性能要好于采用正则表达式查找占位符的String.format方法。MessageFormat > String

三、以下是异常的情况

String message = MessageFormat.format(“name={0}, age={}”, 25, “huhx”); // java.lang.IllegalArgumentException: can’t parse argument number:
String string = String.format(“name=%s, age=%d”, “huhx”); // java.util.MissingFormatArgumentException: Format specifier ‘%d’

两者的实现原理

我们通过下面的简单的例子来分析两者的原理:

public void messageFormat() {
   
    String string = String.format("name=%s, age=%d", "huhx", 25);
    String message = MessageFormat.format("name={1}, age={0}, {1}", 25, "huhx");
    System.out.println(string);
    System.out.println(message);
  }
// name=huhx, age=25
// name=huhx, age=25, huhx

一、String.format的实现原理

String.format内部的实现是一个Formatter,使用了正则表达式来查找占位数据的。我们在这里贴出它实现的源代码。

 1 public Formatter format(Locale l, String format, Object ... args) {
   
 2     ensureOpen();
 3     // index of last argument referenced
 4     int last = -1;
 5     // last ordinary index
 6     int lasto = -1;
 7 
 8     FormatString[] fsa = parse(format);
 9     for (int i = 0; i < fsa.length; i++) {
   
10         FormatString fs = fsa[i];
11         int index = fs.index();
12         try {
   
13             switch (index) {
   
14             case -2:  // fixed string, "%n", or "%%"
15                 fs.print(null, l);
16                 break;
17             case -1:  // relative index
18                 if (last < 0 || (args != null && last > args.length - 1))
19                     throw new MissingFormatArgumentException(fs.toString());
20                 fs.print((args == null ? null : args[last]), l);
21                 break;
22             case 0:  // ordinary index
23                 lasto++;
24                 last = lasto;
25                 if (args != null && lasto > args.length - 1)
26                     throw new MissingFormatArgumentException(fs.toString());
27                 fs.print((args == null ? null : args[lasto]), l);
28                 break;
29             default:  // explicit index
30                 last = index - 1;
31                 if (args != null && last > args.length - 1)
32                     throw new MissingFormatArgumentException(fs.toString());
33                 fs.print((args == null ? null : args[last]), l);
34                 break;
35             }//需要获取资料的朋友请加Q君样:290194256*
36         } catch (IOException x
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值