(以下为新增的Java 17+特性与现代技术栈内容)
Java 17引入了更强大的模式匹配功能,包括instanceof
模式匹配和switch
表达式的模式匹配。这使得代码更加简洁和安全。
**instanceof
// 旧写法
if (obj instanceof String) {
String str = (String) obj;
System.out.println(str.length());
}
// 新写法
if (obj instanceof String str) {
System.out.println(str.length()); // 直接使用str变量
}
switch
**表达式模式匹配示例:**
sealed interface Shape permits Circle, Rectangle { }
record Circle(double radius) implements Shape { }
record Rectangle(double width, double height) implements Shape { }
double calculateArea(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.width() * r.height();
};
}
文本块使多行字符串处理更加便捷,避免了繁琐的转义和连接操作。
示例:
// 旧写法
String html = "<html>\n" +
" <body>\n" +
" <p>Hello, World!</p>\n" +
" </body>\n" +
"</html>";
// 新写法
String html = """
<html>
<body>
<p>Hello, World!</p>
</body>
</html>
""";
记录类是一种不可变的数据类,用于简化POJO的创建。
示例:
// 旧写法
public class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
}
// 新写法
record Person(String name, int age) { }
密封类允许你精确控制哪些类可以继承或实现它,增强了类型安全性。
示例:
sealed interface Animal permits Dog, Cat { }
final class Dog implements Animal { }
final class Cat implements Animal { }
创建REST API示例:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RestController
@RequestMapping("/api/users")
class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
public ResponseEntity<UserDTO> getUser(@PathVariable Long id) {
return userService.getUserById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public UserDTO createUser(@RequestBody @Valid UserDTO userDTO) {
return userService.createUser(userDTO);
}
}
响应式流处理示例:
@Service
public class ProductService {
private final WebClient webClient;
public ProductService(WebClient.Builder builder) {
this.webClient = builder.baseUrl("https://api.products.com").build();
}
public Flux<Product> getProducts() {
return webClient.get().uri("/products")
.retrieve()
.bodyToFlux(Product.class)
.timeout(Duration.ofSeconds(5))
.onErrorResume(e -> Flux.empty());
}
public Mono<Product> getProductById(String id) {
return webClient.get().uri("/products/{id}", id)
.retrieve()
.bodyToMono(Product.class)
.retry(3);
}
}
集合工厂方法与Stream操作示例:
// 不可变集合创建
List<String> names = List.of("Alice", "Bob", "Charlie");
Set<Integer> numbers = Set.of(1, 2, 3, 4);
Map<String, Integer> scores = Map.of("Alice", 95, "Bob", 87);
// Stream API增强
int sum = names.stream()
.filter(name -> name.length() > 4)
.mapToInt(String::length)
.sum();
// 并行流处理
List<Product> products = getProducts();
double totalPrice = products.parallelStream()
.mapToDouble(Product::getPrice)
.sum();
测试示例:
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
void shouldReturnUserWhenFound() {
// 准备测试数据
User user = new User(1L, "test@example.com", "Test User");
when(userRepository.findById(1L)).thenReturn(Optional.of(user));
// 执行测试
Optional<User> result = userService.getUserById(1L);
// 验证结果
assertTrue(result.isPresent());
assertEquals("test@example.com", result.get().getEmail());
verify(userRepository, times(1)).findById(1L);
}
}
两数之和(LeetCode #1):
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
return new int[]{};
}
反转链表(LeetCode #206):
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
单例模式(枚举实现):
public enum Singleton {
INSTANCE;
public void doSomething() {
System.out.println("Singleton method called");
}
}
工厂模式:
public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Circle");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Rectangle");
}
}
public class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
return switch (shapeType.toLowerCase()) {
case "circle" -> new Circle();
case "rectangle" -> new Rectangle();
default -> throw new IllegalArgumentException("Unknown shape type: " + shapeType);
};
}
}
实体与Repository示例:
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
private double price;
// getters, setters, constructors
}
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findByNameContaining(String keyword);
@Query("SELECT p FROM Product p WHERE p.price > :minPrice")
List<Product> findByPriceGreaterThan(@Param("minPrice") double minPrice);
}
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final InventoryService inventoryService;
@Transactional
public Order createOrder(Order order) {
// 扣减库存
inventoryService.decreaseStock(order.getProductId(), order.getQuantity());
// 保存订单
return orderRepository.save(order);
}
}
示例:
// 旧写法
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
});
// 新写法
names.sort(String::compareTo);
// Stream操作
names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.forEach(System.out::println);
# 使用jcmd查看JVM信息
jcmd <PID> VM.info
# 生成堆转储文件
jcmd <PID> GC.heap_dump heapdump.hprof
# 使用jstat监控GC情况
jstat -gc <PID> 1000 10 # 每1秒采样一次,共采样10次
以上新增内容涵盖了Java 17+的最新特性、现代开发技术栈以及常见算法与设计模式的实战应用。在准备校招笔试时,建议结合这些技术点进行系统复习,并通过实际编码练习加深理解。
Java 研发,2025 春季校招,笔试题解析,校招笔试,Java 面试题,高效学习指南,Java 知识点,数据结构,算法,面向对象编程,JVM,Spring 框架,数据库,网络编程,校招求职
资源地址:
https://pan.quark.cn/s/14fcf913bae6
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。