假设以下内容:
String example = "something";
String firstLetter = "";
以下分配方式firstLetter可能会影响性能,请注意是否存在差异;哪个最好,为什么?
firstLetter = String.valueOf(example.charAt(0));
firstLetter = Character.toString(example.charAt(0));
firstLetter = example.substring(0, 1);
返回第一个字母为a的原因String是,这是在Hadoop中运行的,并且需要将字符串分配给Text类型,该字符串将从方法中firstLetter输出为a ,例如:keymap()
public class FirstLetterMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
String line = new String();
Text firstLetter = new Text();
IntWritable wordLength = new IntWritable();
@Override
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
line = value.toString();
for (String word : line.split("\\W+")){
if (word.length() > 0) {
// ---------------------------------------------
// firstLetter assignment
firstLetter.set(String.valueOf(word.charAt(0)).toLowerCase());
// ---------------------------------------------
wordLength.set(word.length());
context.write(firstLetter, wordLength);
}
}
}
}