StringBuilder builder1=new StringBuilder("Hello13"); String str14=new String(builder1); System.out.println(str14);
时间: 2023-11-12 20:38:48 浏览: 55
这段代码的作用是将 StringBuilder 对象 builder1 中的内容转换成字符串,并将其赋值给 str14,然后输出 str14 的值。
具体来说,这里首先创建了一个 StringBuilder 对象 builder1,其初始值为 "Hello13"。然后通过调用 String 类的构造方法将 builder1 转换成字符串,并将其赋值给 str14。最后,使用 System.out.println() 方法输出 str14 的值,结果为 "Hello13"。
相关问题
请设计一个类型,提供如下方法 提示 要统计每个单词出现的次数,由于一个方法不能返回2种类型,我们需要把单词和它的出现次数封装到一个类中 去,所以,可以定义一个类型如下: 由于我们统计的有多个单词,所以,我们上面的 countSize 方法的返回类型就可以设计成 WordBean[],如下: public class PatternDemo { //此方法用来统计 content 中的英文单词个数, 请使用正则表达式来做,单词的正则表达式请自行编写, public int countWords(CharSequence content) { ... } //此方法返回一串固定的字符串,已写好,可以直接用。 public StringBuilder getContent() { //此方法的内容如下: StringBuilder builder = new StringBuilder(); builder.append("Hooray! It's snowing! It's time to make a snowman.James runs out. He makes a big pile of snow. He puts a big snowball on top. He adds a scarf and a hat. He adds an orange for the nose. He adds coal for the eyes and buttons.In the evening, James opens the door. What does he see? The snowman is moving! James invites him in. The snowman has never been inside a house. He says hello to the cat. He plays with paper towels.A moment later, the snowman takes James's hand and goes out.They go up, up, up into the air! They are flying! What a wonderful night!The next morning, James jumps out of bed. He runs to the door.He wants to thank the snowman. But he's gone."); // return builder; } //此方法统计出每个单词[不考虑大小写]出现的次数,数据结构请自行定义,设计如下: public ? countSize(CharSequence content) { //TODO ... } //注:int[]结构来存放结果 } public class WordBean { //属性 private String word; //单词 private int count; //出次 //TODO 请自行完成构造、getter/setter、toString、等相关方法 } public WordBean[] countSize(CharSequence content) { //TODO ... } 最后写一个调用者类,来测试你的实现,如下: public class UsePatternDemo() { public static void main(String[] args) { //TODO ... }
下面是一个实现了 countSize 方法和 WordBean 类的示例代码:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternDemo {
public int countWords(CharSequence content) {
// 定义单词的正则表达式
String patternStr = "\\b\\w+\\b";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(content);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
public WordBean[] countSize(CharSequence content) {
// 定义单词的正则表达式
String patternStr = "\\b\\w+\\b";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(content);
// 使用 Map 来统计每个单词的出现次数
Map<String, Integer> wordCountMap = new HashMap<>();
while (matcher.find()) {
String word = matcher.group().toLowerCase();
if (wordCountMap.containsKey(word)) {
wordCountMap.put(word, wordCountMap.get(word) + 1);
} else {
wordCountMap.put(word, 1);
}
}
// 将统计结果封装到 WordBean 数组中
WordBean[] result = new WordBean[wordCountMap.size()];
int i = 0;
for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) {
result[i++] = new WordBean(entry.getKey(), entry.getValue());
}
return result;
}
public StringBuilder getContent() {
StringBuilder builder = new StringBuilder();
builder.append("Hooray! It's snowing! It's time to make a snowman.James runs out. He makes a big pile of snow. He puts a big snowball on top. He adds a scarf and a hat. He adds an orange for the nose. He adds coal for the eyes and buttons.In the evening, James opens the door. What does he see? The snowman is moving! James invites him in. The snowman has never been inside a house. He says hello to the cat. He plays with paper towels.A moment later, the snowman takes James's hand and goes out.They go up, up, up into the air! They are flying! What a wonderful night!The next morning, James jumps out of bed. He runs to the door.He wants to thank the snowman. But he's gone.");
return builder;
}
}
public class WordBean {
private String word;
private int count;
public WordBean(String word, int count) {
this.word = word;
this.count = count;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return "WordBean{" +
"word='" + word + '\'' +
", count=" + count +
'}';
}
}
public class UsePatternDemo {
public static void main(String[] args) {
PatternDemo patternDemo = new PatternDemo();
StringBuilder content = patternDemo.getContent();
WordBean[] result = patternDemo.countSize(content);
for (WordBean wordBean : result) {
System.out.println(wordBean);
}
}
}
```
在这个示例代码中,我们封装了一个 WordBean 类,用来表示单词和它的出现次数。在 countSize 方法中,我们使用正则表达式来匹配文本中的单词,并使用 HashMap 来统计每个单词的出现次数。最后,我们将统计结果封装到 WordBean 数组中返回。在调用者类 UsePatternDemo 中,我们可以测试我们的实现是否正确。
String,StringBuffer,StringBuilder
### Java 中 `String`、`StringBuffer` 和 `StringBuilder` 的区别及使用场景
#### 1. `String`
`String` 是不可变类,这意味着一旦创建了一个 `String` 对象,其内容就不能被修改[^1]。每次对 `String` 进行操作时都会生成新的对象。
```java
// 创建两个相同的字符串常量池中的实例不会重复创建
String str1 = "hello";
String str2 = "world";
// 字符串拼接会创建新对象
String result = str1 + ", " + str2;
```
由于这种特性,在频繁进行字符串连接的情况下效率较低,因为会产生大量的临时对象并增加垃圾回收的压力。
#### 2. `StringBuffer`
`StringBuffer` 是可变字符序列,并且是线程安全的。它提供了一系列的方法来高效地构建和操纵字符串数据[^2]。然而,为了实现同步机制,性能上可能会有所牺牲。
```java
StringBuffer buffer = new StringBuffer();
buffer.append("hello");
buffer.append(", ");
buffer.append("world");
System.out.println(buffer.toString());
```
当多个线程可能同时访问同一个缓冲区时推荐使用此类型;但如果仅限于单一线程环境,则可以考虑更高效的替代方案。
#### 3. `StringBuilder`
类似于 `StringBuffer` ,但是它是非线程安全版本,因此通常情况下它的执行速度更快一些[^3]。对于大多数应用程序来说,除非特别强调多线程安全性,否则应优先选用 `StringBuilder` 来提高程序运行效率。
```java
StringBuilder builder = new StringBuilder();
builder.append("hello");
builder.append(", ");
builder.append("world");
System.out.println(builder.toString());
```
综上所述:
- 如果需要处理固定不变的文字信息,请选择 `String`;
- 当涉及到大量动态变化的数据并且处于并发环境中时适合采用 `StringBuffer`;
- 而在不需要担心竞态条件的前提下追求更高性能的话就应当倾向于 `StringBuilder`。
阅读全文