我想用Java Map填充以下文本的占位符.
String text = "Media file %s of size %s has been uploaded";
Run Code Online (Sandbox Code Playgroud)
这就是我在地图中输入值的方式.
Map<String, String> properties = new HashMap<>();
properties.put(MediaFile.fileName, "Sample 001");
properties.put(MediaFile.fileSize, "2Mb");
Run Code Online (Sandbox Code Playgroud)
我希望输出文本是这样的.
Media file Sample 001 of size 2Mb has been uploaded
Run Code Online (Sandbox Code Playgroud)
但我把它作为输出.
Media file 2Mb of size 2Mb has been uploaded
Run Code Online (Sandbox Code Playgroud)
我创建了一个类来保存变量fileName和fileSize.
public class MediaFile {
public static String fileName;
public static String fileSize;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我像下面一样使用它,它工作正常.但我想分开fileName和fileSize.但我不确定我是否正确实现了MediaFile类.谁能告诉我我的代码有什么问题?
properties.put("fileName", "Sample 001");
properties.put("fileSize", "2Mb");
Run Code Online (Sandbox Code Playgroud)
当您使用MediaFile.fileName和MediaFile.fileSize作为键时,两者都包含相同的值 - null- 因为您从未初始化它们.因此,第二个properties.put()替换第一个的值properties.put()(因为HashMaps不允许重复键).
您可能想要使用常量:
public class MediaFile {
public static final String fileName = "fileName";
public static final String fileSize = "fileSize";
}
Run Code Online (Sandbox Code Playgroud)
现在,您的常量初始化为不同的值,您的原始代码将起作用.