1、StringBuilder:
测试代码1:
package stringbuilder.com;
import java.util.ArrayList;
import java.util.List;
public class StringBuilderExample {
public static void main(String[] args) {
// 初始化StringBuilder
StringBuilder sb = new StringBuilder("This is a complex example using StringBuilder. ");
// 添加不同类型的数据
sb.append("It demonstrates ").append(42).append(" different operations. ");
// 使用循环构建字符串
List<String> items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
sb.append("The list contains: ");
for (String item : items) {
sb.append(item).append(", ");
}
// 移除最后一个逗号和空格
if (sb.length() > 0 && sb.charAt(sb.length() - 1) == ',') {
sb.setLength(sb.length() - 2); // 移除逗号和空格
}
// 反转部分字符串
String partialString = sb.substring(0, sb.indexOf("list contains:") + "list contains:".length()).trim();
StringBuilder reversedPartial = new StringBuilder(partialString).reverse();
// 在StringBuilder中插入反转后的部分字符串
sb.insert(0, "Reversed partial: ").insert(0, reversedPartial).append("\n");
// 转换并打印结果
System.out.println(sb.toString());
// 字符串与另一个StringBuilder合并
StringBuilder anotherSb = new StringBuilder("Additional information: ");
anotherSb.append("This is more data to be appended.");
// 合并两个StringBuilder
sb.append(anotherSb);
// 打印最终结果
System.out.println(sb.toString());
}
}
运行结果如下:
测试代码2:
package stringbuilder.com;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class StringBuilderTest {
private enum LogLevel {
DEBUG, INFO, WARN, ERROR
}
private static final Map<LogLevel, Set<String>> logMessages = new HashMap<>();
static {
// 初始化日志级别集合
for (LogLevel level : LogLevel.values()) {
logMessages.put(level, new HashSet<>());
}
}
public static void main(String[] args) {
// 日志记录
log(LogLevel.INFO, "System starting up...");
log(LogLevel.DEBUG, "Initializing configuration...");
log(LogLevel.WARN, "Old configuration file found, using defaults.");
log(LogLevel.ERROR, "Failed to connect to database!");
// WARN和ERROR级别的日志
printLogs(LogLevel.WARN, LogLevel.ERROR);
// 使用StringBuilder构建更复杂的日志消息
StringBuilder complexMessage = buildComplexLogMessage("UserActivity", "user123", LogLevel.INFO, "Logged in successfully.");
log(complexMessage);
// 打印所有WARN和ERROR级别的日志,包括新添加的
printLogs(LogLevel.WARN, LogLevel.ERROR);
}
public static void log(LogLevel level, String message) {
logMessages.get(level).add(formatLogMessage(level, message));
}
public static void log(StringBuilder message) {
// INFO级别的日志
log(LogLevel.INFO, message.toString());
}
private static String formatLogMessage(LogLevel level, String message) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return String.format("[%s] [%s] %s", formatter.format(LocalDateTime.now()), level.name(), message);
}
public static void printLogs(LogLevel... levels) {
for (LogLevel level : levels) {
System.out.println("--- " + level.name() + " LOGS ---");
for (String msg : logMessages.getOrDefault(level, Set.of())) {
System.out.println(msg);
}
if (logMessages.getOrDefault(level, Set.of()).isEmpty()) {
System.out.println("No " + level.name() + " logs found.");
}
}
}
public static StringBuilder buildComplexLogMessage(String category, String user, LogLevel level, String message) {
StringBuilder sb = new StringBuilder();
sb.append("[")
.append(category)
.append("]")
.append(" [")
.append(user)
.append("]")
.append(" [")
.append(level.name())
.append("] ")
.append(message);
// 额外的系统信息
if (level == LogLevel.ERROR) {
sb.append(" [System Info: Memory Usage High]");
}
return sb;
}
}
运行结果如下:
测试代码3:
package stringbuilder.com;
public class ComplexStringBuilderTest {
@SuppressWarnings("unused")
public static void main(String[] args) {
// 用户活动记录中的信息
String userId = "U12345";
String userName = "John Doe";
String activityType = "Login";
String ipAddress = "192.168.1.1";
boolean isSuccess = true;
String errorMessage = null; // 假设登录成功,没有错误信息
String additionalInfo = "User logged in from a trusted IP.";
// 初始化StringBuilder构建日志消息
StringBuilder logMessage = new StringBuilder();
// 添加基础信息
logMessage.append("Log Entry for User ").append(userId).append(" (").append(userName).append("):\n");
logMessage.append("Activity Type: ").append(activityType).append("\n");
logMessage.append("IP Address: ").append(ipAddress).append("\n");
// 根据是否成功添加不同的信息
if (isSuccess) {
logMessage.append("Activity Result: Success\n");
} else {
logMessage.append("Activity Result: Failed\n");
if (errorMessage != null && !errorMessage.isEmpty())
logMessage.append("Error Message: ").append(errorMessage).append("\n");
}
// 添加附加信息
if (additionalInfo != null && !additionalInfo.isEmpty()) {
logMessage.append("Additional Information: ").append(additionalInfo).append("\n");
}
// 记录活动发生的时间
String timestamp = "2023-04-01T12:34:56Z";
logMessage.append("Timestamp: ").append(timestamp).append("\n");
// 输出构建的日志消息
System.out.println(logMessage.toString());
}
}
运行结果如下:
测试代码4:
package stringbuilder.com;
public class OrderInfoBuilder {
public static void main(String[] args) {
// 订单数据
String orderId = "O00123456";
String customerName = "John Doe";
String customerEmail = "john.doe@example.com";
double totalAmount = 199.99;
// 订单包含多个商品
Product product1 = new Product("Product A", 1, 99.99);
Product product2 = new Product("Product B", 2, 50.00);
Product[] products = {product1, product2};
// 使用StringBuilder构建订单信息
StringBuilder orderInfo = buildOrderInfo(orderId, customerName, customerEmail, totalAmount, products);
// 输出订单信息
System.out.println(orderInfo.toString());
}
public static StringBuilder buildOrderInfo(String orderId, String customerName, String customerEmail, double totalAmount, Product[] products) {
StringBuilder sb = new StringBuilder();
// 添加订单基本信息
sb.append("Order Information:\n");
sb.append("Order ID: ").append(orderId).append("\n");
sb.append("Customer Name: ").append(customerName).append("\n");
sb.append("Customer Email: ").append(customerEmail).append("\n");
sb.append("Total Amount: $").append(String.format("%.2f", totalAmount)).append("\n");
// 添加商品列表
sb.append("\nItems in Order:\n");
for (Product product : products) {
sb.append(String.format(" - %s (Quantity: %d, Price: $%.2f)\n",
product.getName(), product.getQuantity(), product.getPrice()));
}
// 订单处理的额外信息
String processingStatus = "Processing";
String shippingAddress = "1234 Main St, Anytown, USA";
// 订单处理状态
sb.append("\nOrder Processing Status: ").append(processingStatus).append("\n");
// 配送地址
if (shippingAddress != null && !shippingAddress.isEmpty()) {
sb.append("Shipping Address: ").append(shippingAddress).append("\n");
}
// 订单备注信息
String remarks = ""; // 来自用户输入或数据库
// 订单备注
if (remarks != null && !remarks.isEmpty()) {
sb.append("\nOrder Remarks: ").append(remarks).append("\n");
}
// 时间戳
String timestamp = "2023-04-01T12:34:56Z";
sb.append("\nOrder Timestamp: ").append(timestamp).append("\n");
return sb;
}
// 订单中的商品类
static class Product {
private String name;
private int quantity;
private double price;
public Product(String name, int quantity, double price) {
this.name = name;
this.quantity = quantity;
this.price = price;
}
public String getName() {
return name;
}
public int getQuantity() {
return quantity;
}
public double getPrice() {
return price;
}
}
}
运行结果如下:
2、 StringBuilder与StringBuffer的区别:
测试代码:
package stringbuilder.com;
public class ThreadSafetyDemo {
public static void main(String[] args) {
//使用StringBuilder(非线程安全)
//创建两个线程(thread1和thread2),它们同时尝试向同一个StringBuilder实例追加内容。
//由于StringBuilder不是线程安全的,这两个线程可能会相互干扰,导致最终的字符串内容不可预测。
//StringBuilder的输出是乱序的。
StringBuilder sbNonThreadSafe = new StringBuilder();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
sbNonThreadSafe.append("Thread 1: ");
sbNonThreadSafe.append(i);
sbNonThreadSafe.append("\n");
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
sbNonThreadSafe.append("Thread 2: ");
sbNonThreadSafe.append(i);
sbNonThreadSafe.append("\n");
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("StringBuilder result (may be unpredictable):");
System.out.println(sbNonThreadSafe.toString());
// 使用StringBuffer(线程安全)
//创建了两个新的线程(thread3和thread4),使用StringBuffer实例。
//StringBuffer是线程安全的,即使两个线程同时尝试修改它,最终的字符串内容也将是可预测的。
//每个线程将按顺序追加其内容,而不会出现内容错乱的情况。
//StringBuffer的输出是有序。
StringBuffer sbThreadSafe = new StringBuffer();
Thread thread3 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
sbThreadSafe.append("Thread 3: ");
sbThreadSafe.append(i);
sbThreadSafe.append("\n");
}
});
Thread thread4 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
sbThreadSafe.append("Thread 4: ");
sbThreadSafe.append(i);
sbThreadSafe.append("\n");
}
});
thread3.start();
thread4.start();
try {
thread3.join();
thread4.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\nStringBuffer result (predictable):");
System.out.println(sbThreadSafe.toString());
}
}
运行结果如下: