第491集精通Java | 字数总计: 5.3k | 阅读时长: 25分钟 | 阅读量:
精通Java 1. 概述 1.1 Java的重要性 Java 是一门面向对象的编程语言,具有跨平台、安全性高、生态丰富等特点,是企业级应用开发的主流语言。
本文内容 :
Java基础 :语言特性、语法基础
面向对象 :封装、继承、多态
集合框架 :List、Set、Map等集合
并发编程 :多线程、线程池、并发工具
JVM原理 :内存模型、垃圾回收、性能调优
设计模式 :常用设计模式实战
框架使用 :Spring、MyBatis等框架
性能优化 :Java性能优化技巧
1.2 本文内容结构 本文将从以下几个方面深入探讨如何精通Java:
Java基础 :语言特性和语法
面向对象编程 :OOP核心概念
集合框架 :常用集合的使用
并发编程 :多线程和并发处理
JVM原理 :Java虚拟机深入理解
设计模式 :常用设计模式实战
框架应用 :主流框架的使用
性能优化 :Java性能优化技巧
2. Java基础 2.1 Java语言特性 2.1.1 核心特性 Java核心特性 :
面向对象 :封装、继承、多态
平台无关性 :一次编写,到处运行
自动内存管理 :垃圾回收机制
多线程支持 :内置多线程支持
安全性 :沙箱机制,安全性高
示例代码 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 public class JavaFeatures { private String name; private int age; public String getName () { return name; } public void setName (String name) { this .name = name; } public void multiThreadExample () { Thread thread = new Thread (() -> { System.out.println("Thread running" ); }); thread.start(); } public void exceptionExample () { try { int result = 10 / 0 ; } catch (ArithmeticException e) { System.out.println("Exception: " + e.getMessage()); } } }
2.2 数据类型 2.2.1 基本数据类型 Java基本数据类型 :
类型
大小
范围
默认值
byte
1字节
-128 ~ 127
0
short
2字节
-32768 ~ 32767
0
int
4字节
-2^31 ~ 2^31-1
0
long
8字节
-2^63 ~ 2^63-1
0L
float
4字节
约±3.4E38
0.0f
double
8字节
约±1.7E308
0.0d
char
2字节
0 ~ 65535
‘\u0000’
boolean
1位
true/false
false
包装类型 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class DataTypeExample { public void basicTypeExample () { int a = 10 ; double b = 3.14 ; boolean c = true ; Integer a1 = 10 ; int a2 = a1; String str = "Hello Java" ; int [] array = {1 , 2 , 3 , 4 , 5 }; String[] strings = new String [10 ]; } }
2.3 控制结构 2.3.1 条件语句和循环 控制结构示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 public class ControlStructure { public void ifExample (int score) { if (score >= 90 ) { System.out.println("优秀" ); } else if (score >= 80 ) { System.out.println("良好" ); } else if (score >= 60 ) { System.out.println("及格" ); } else { System.out.println("不及格" ); } switch (score / 10 ) { case 10 : case 9 : System.out.println("优秀" ); break ; case 8 : System.out.println("良好" ); break ; default : System.out.println("其他" ); } } public void loopExample () { for (int i = 0 ; i < 10 ; i++) { System.out.println(i); } int [] array = {1 , 2 , 3 , 4 , 5 }; for (int num : array) { System.out.println(num); } int i = 0 ; while (i < 10 ) { System.out.println(i); i++; } int j = 0 ; do { System.out.println(j); j++; } while (j < 10 ); } }
3. 面向对象编程 3.1 封装 3.1.1 封装的概念 封装 :将数据和方法包装在类中,隐藏内部实现细节,只暴露必要的接口。
封装示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 public class BankAccount { private String accountNumber; private double balance; public BankAccount (String accountNumber, double balance) { this .accountNumber = accountNumber; this .balance = balance; } public double getBalance () { return balance; } public void deposit (double amount) { if (amount > 0 ) { balance += amount; System.out.println("存款成功,余额:" + balance); } else { System.out.println("存款金额必须大于0" ); } } public void withdraw (double amount) { if (amount > 0 && amount <= balance) { balance -= amount; System.out.println("取款成功,余额:" + balance); } else { System.out.println("取款失败,余额不足或金额无效" ); } } }
3.2 继承 3.2.1 继承的概念 继承 :子类继承父类的属性和方法,实现代码复用。
继承示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 public class Animal { protected String name; protected int age; public Animal (String name, int age) { this .name = name; this .age = age; } public void eat () { System.out.println(name + "正在吃东西" ); } public void sleep () { System.out.println(name + "正在睡觉" ); } } public class Dog extends Animal { private String breed; public Dog (String name, int age, String breed) { super (name, age); this .breed = breed; } @Override public void eat () { System.out.println(name + "(" + breed + ")正在吃狗粮" ); } public void bark () { System.out.println(name + "正在叫:汪汪汪" ); } }
3.3 多态 3.3.1 多态的概念 多态 :同一接口,不同实现。包括编译时多态(方法重载)和运行时多态(方法重写)。
多态示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 public interface Shape { double calculateArea () ; double calculatePerimeter () ; } public class Circle implements Shape { private double radius; public Circle (double radius) { this .radius = radius; } @Override public double calculateArea () { return Math.PI * radius * radius; } @Override public double calculatePerimeter () { return 2 * Math.PI * radius; } } public class Rectangle implements Shape { private double width; private double height; public Rectangle (double width, double height) { this .width = width; this .height = height; } @Override public double calculateArea () { return width * height; } @Override public double calculatePerimeter () { return 2 * (width + height); } } public class PolymorphismExample { public static void main (String[] args) { Shape circle = new Circle (5 ); Shape rectangle = new Rectangle (4 , 6 ); printShapeInfo(circle); printShapeInfo(rectangle); } public static void printShapeInfo (Shape shape) { System.out.println("面积:" + shape.calculateArea()); System.out.println("周长:" + shape.calculatePerimeter()); } }
3.4 抽象类和接口 3.4.1 抽象类与接口的区别 抽象类 :包含抽象方法的类,不能实例化。
接口 :定义一组方法规范,Java 8支持默认方法和静态方法。
对比示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 public abstract class AbstractAnimal { protected String name; public abstract void makeSound () ; public void eat () { System.out.println(name + "正在吃东西" ); } } public interface Flyable { void fly () ; default void takeOff () { System.out.println("准备起飞" ); } static void showInfo () { System.out.println("这是一个飞行接口" ); } } public class Bird extends AbstractAnimal implements Flyable { public Bird (String name) { this .name = name; } @Override public void makeSound () { System.out.println(name + "在叫:啾啾啾" ); } @Override public void fly () { System.out.println(name + "正在飞行" ); } }
4. 集合框架 4.1 List集合 4.1.1 ArrayList和LinkedList List接口 :有序、可重复的集合。
ArrayList vs LinkedList :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 import java.util.*;public class ListExample { public void arrayListExample () { List<String> arrayList = new ArrayList <>(); arrayList.add("Java" ); arrayList.add("Python" ); arrayList.add("C++" ); for (String lang : arrayList) { System.out.println(lang); } String first = arrayList.get(0 ); int index = arrayList.indexOf("Python" ); } public void linkedListExample () { List<String> linkedList = new LinkedList <>(); linkedList.add("Java" ); linkedList.add("Python" ); linkedList.add("C++" ); linkedList.add(0 , "Go" ); linkedList.add("Rust" ); } public void vectorExample () { Vector<String> vector = new Vector <>(); vector.add("Java" ); List<String> syncList = Collections.synchronizedList(new ArrayList <>()); } }
4.2 Set集合 4.2.1 HashSet和TreeSet Set接口 :无序、不可重复的集合。
Set示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 import java.util.*;public class SetExample { public void hashSetExample () { Set<String> hashSet = new HashSet <>(); hashSet.add("Java" ); hashSet.add("Python" ); hashSet.add("Java" ); for (String lang : hashSet) { System.out.println(lang); } boolean contains = hashSet.contains("Java" ); } public void treeSetExample () { Set<String> treeSet = new TreeSet <>(); treeSet.add("Java" ); treeSet.add("Python" ); treeSet.add("C++" ); for (String lang : treeSet) { System.out.println(lang); } } public void linkedHashSetExample () { Set<String> linkedHashSet = new LinkedHashSet <>(); linkedHashSet.add("Java" ); linkedHashSet.add("Python" ); linkedHashSet.add("C++" ); for (String lang : linkedHashSet) { System.out.println(lang); } } }
4.3 Map集合 4.3.1 HashMap和TreeMap Map接口 :键值对映射。
Map示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 import java.util.*;public class MapExample { public void hashMapExample () { Map<String, Integer> hashMap = new HashMap <>(); hashMap.put("Java" , 1 ); hashMap.put("Python" , 2 ); hashMap.put("C++" , 3 ); Integer value = hashMap.get("Java" ); for (Map.Entry<String, Integer> entry : hashMap.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } for (String key : hashMap.keySet()) { System.out.println(key); } for (Integer val : hashMap.values()) { System.out.println(val); } } public void treeMapExample () { Map<String, Integer> treeMap = new TreeMap <>(); treeMap.put("Java" , 1 ); treeMap.put("Python" , 2 ); treeMap.put("C++" , 3 ); for (Map.Entry<String, Integer> entry : treeMap.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } } public void concurrentHashMapExample () { Map<String, Integer> concurrentMap = new ConcurrentHashMap <>(); concurrentMap.put("Java" , 1 ); concurrentMap.put("Python" , 2 ); concurrentMap.computeIfAbsent("C++" , k -> 3 ); } }
5. 并发编程 5.1 多线程基础 5.1.1 线程创建 创建线程的方式 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 public class ThreadExample { static class MyThread extends Thread { @Override public void run () { System.out.println("Thread running: " + Thread.currentThread().getName()); } } static class MyRunnable implements Runnable { @Override public void run () { System.out.println("Runnable running: " + Thread.currentThread().getName()); } } static class MyCallable implements Callable <String> { @Override public String call () throws Exception { return "Callable result: " + Thread.currentThread().getName(); } } public static void main (String[] args) throws Exception { Thread thread1 = new MyThread (); thread1.start(); Thread thread2 = new Thread (new MyRunnable ()); thread2.start(); Thread thread3 = new Thread (() -> { System.out.println("Lambda thread running" ); }); thread3.start(); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(new MyCallable ()); String result = future.get(); System.out.println(result); executor.shutdown(); } }
5.2 线程同步 5.2.1 synchronized和Lock 线程同步 :保证多线程访问共享资源的安全性。
同步示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 public class SynchronizationExample { private int count = 0 ; private final Object lock = new Object (); private final ReentrantLock reentrantLock = new ReentrantLock (); public synchronized void increment1 () { count++; } public void increment2 () { synchronized (lock) { count++; } } public void increment3 () { reentrantLock.lock(); try { count++; } finally { reentrantLock.unlock(); } } private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock (); public void read () { readWriteLock.readLock().lock(); try { System.out.println("Reading: " + count); } finally { readWriteLock.readLock().unlock(); } } public void write () { readWriteLock.writeLock().lock(); try { count++; } finally { readWriteLock.writeLock().unlock(); } } }
5.3 线程池 5.3.1 线程池的使用 线程池 :复用线程,提高性能。
线程池示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 import java.util.concurrent.*;public class ThreadPoolExample { public void executorServiceExample () { ExecutorService executor = Executors.newFixedThreadPool(10 ); for (int i = 0 ; i < 100 ; i++) { final int taskId = i; executor.submit(() -> { System.out.println("Task " + taskId + " running in " + Thread.currentThread().getName()); }); } executor.shutdown(); try { if (!executor.awaitTermination(60 , TimeUnit.SECONDS)) { executor.shutdownNow(); } } catch (InterruptedException e) { executor.shutdownNow(); } } public void customThreadPoolExample () { ThreadPoolExecutor executor = new ThreadPoolExecutor ( 5 , 10 , 60L , TimeUnit.SECONDS, new LinkedBlockingQueue <>(100 ), new ThreadFactory () { @Override public Thread newThread (Runnable r) { Thread thread = new Thread (r); thread.setName("CustomThread-" + thread.getId()); return thread; } }, new ThreadPoolExecutor .CallerRunsPolicy() ); executor.submit(() -> System.out.println("Custom thread pool task" )); executor.shutdown(); } }
5.4 并发工具类 5.4.1 CountDownLatch、CyclicBarrier、Semaphore 并发工具类 :简化并发编程。
工具类示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 import java.util.concurrent.*;public class ConcurrentToolsExample { public void countDownLatchExample () throws InterruptedException { CountDownLatch latch = new CountDownLatch (3 ); for (int i = 0 ; i < 3 ; i++) { new Thread (() -> { System.out.println("Task completed" ); latch.countDown(); }).start(); } latch.await(); System.out.println("All tasks completed" ); } public void cyclicBarrierExample () { CyclicBarrier barrier = new CyclicBarrier (3 , () -> { System.out.println("All threads reached barrier" ); }); for (int i = 0 ; i < 3 ; i++) { new Thread (() -> { try { System.out.println("Thread waiting at barrier" ); barrier.await(); System.out.println("Thread passed barrier" ); } catch (Exception e) { e.printStackTrace(); } }).start(); } } public void semaphoreExample () { Semaphore semaphore = new Semaphore (3 ); for (int i = 0 ; i < 10 ; i++) { new Thread (() -> { try { semaphore.acquire(); System.out.println("Thread running: " + Thread.currentThread().getName()); Thread.sleep(1000 ); semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); } } public void completableFutureExample () { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { return "Hello" ; }).thenApply(s -> s + " World" ) .thenApply(String::toUpperCase); future.thenAccept(result -> { System.out.println("Result: " + result); }); } }
6. JVM原理 6.1 内存模型 6.1.1 JVM内存结构 JVM内存结构 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class JVMMemoryModel { private static String staticField = "Static Field" ; public void heapExample () { Object obj = new Object (); } public void stackExample (int param) { int localVar = 10 ; } }
内存参数调优 :
1 2 3 4 5 6 7 8 9 java -Xms2g -Xmx4g -Xmn1g -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m -XX:+UseG1GC -XX:MaxGCPauseMillis=200 YourApplication
6.2 垃圾回收 6.2.1 GC算法和收集器 垃圾回收算法 :
标记-清除 :标记垃圾对象,清除
标记-复制 :复制存活对象到新区域
标记-整理 :标记后整理,消除碎片
垃圾回收器 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 public class GarbageCollectionExample { public void gcExample () { for (int i = 0 ; i < 1000000 ; i++) { Object obj = new Object (); } System.gc(); } public void objectLifecycle () { MyObject obj = new MyObject (); obj.doSomething(); obj = null ; } }
GC调优 :
1 2 3 4 5 6 7 8 9 10 11 java -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:gc.log YourApplication java -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:G1HeapRegionSize=16m YourApplication
6.3 性能调优 6.3.1 JVM性能调优 性能调优技巧 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 public class PerformanceOptimization { public void avoidUnnecessaryObjects () { String str1 = new String ("Hello" ); String str2 = "Hello" ; } public void stringBuilderExample () { String result = "" ; for (int i = 0 ; i < 1000 ; i++) { result += i; } StringBuilder sb = new StringBuilder (); for (int i = 0 ; i < 1000 ; i++) { sb.append(i); } String result2 = sb.toString(); } public void collectionOptimization () { List<String> list = new ArrayList <>(1000 ); Map<String, String> map = new HashMap <>(1000 ); } public void objectPoolExample () { } }
7. 设计模式 7.1 单例模式 7.1.1 单例模式实现 单例模式 :确保一个类只有一个实例。
实现方式 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 public class Singleton1 { private static final Singleton1 INSTANCE = new Singleton1 (); private Singleton1 () {} public static Singleton1 getInstance () { return INSTANCE; } } public class Singleton2 { private static volatile Singleton2 INSTANCE; private Singleton2 () {} public static Singleton2 getInstance () { if (INSTANCE == null ) { synchronized (Singleton2.class) { if (INSTANCE == null ) { INSTANCE = new Singleton2 (); } } } return INSTANCE; } } public class Singleton3 { private Singleton3 () {} private static class Holder { private static final Singleton3 INSTANCE = new Singleton3 (); } public static Singleton3 getInstance () { return Holder.INSTANCE; } } public enum Singleton4 { INSTANCE; public void doSomething () { System.out.println("Singleton method" ); } }
7.2 工厂模式 7.2.1 工厂模式实现 工厂模式 :创建对象而不暴露创建逻辑。
工厂模式示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 public interface Product { void use () ; } public class ProductA implements Product { @Override public void use () { System.out.println("Using Product A" ); } } public class ProductB implements Product { @Override public void use () { System.out.println("Using Product B" ); } } public interface ProductFactory { Product createProduct () ; } public class ProductAFactory implements ProductFactory { @Override public Product createProduct () { return new ProductA (); } } public class ProductBFactory implements ProductFactory { @Override public Product createProduct () { return new ProductB (); } } public class FactoryExample { public static void main (String[] args) { ProductFactory factory = new ProductAFactory (); Product product = factory.createProduct(); product.use(); } }
7.3 观察者模式 7.3.1 观察者模式实现 观察者模式 :定义对象间一对多的依赖关系。
观察者模式示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 import java.util.*;public interface Observer { void update (String message) ; } public class Subject { private List<Observer> observers = new ArrayList <>(); public void addObserver (Observer observer) { observers.add(observer); } public void removeObserver (Observer observer) { observers.remove(observer); } public void notifyObservers (String message) { for (Observer observer : observers) { observer.update(message); } } } public class ConcreteObserver implements Observer { private String name; public ConcreteObserver (String name) { this .name = name; } @Override public void update (String message) { System.out.println(name + " received: " + message); } } public class ObserverExample { public static void main (String[] args) { Subject subject = new Subject (); subject.addObserver(new ConcreteObserver ("Observer 1" )); subject.addObserver(new ConcreteObserver ("Observer 2" )); subject.notifyObservers("Hello Observers!" ); } }
8. 框架应用 8.1 Spring框架 8.1.1 Spring核心概念 Spring框架 :IoC容器和AOP框架。
Spring示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 public interface UserService { void saveUser (User user) ; User getUserById (Long id) ; } @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Override @Transactional public void saveUser (User user) { userRepository.save(user); } @Override public User getUserById (Long id) { return userRepository.findById(id); } } @Repository public class UserRepository { public void save (User user) { } public User findById (Long id) { return null ; } } @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @PostMapping public ResponseEntity<String> createUser (@RequestBody User user) { userService.saveUser(user); return ResponseEntity.ok("User created" ); } @GetMapping("/{id}") public ResponseEntity<User> getUser (@PathVariable Long id) { User user = userService.getUserById(id); return ResponseEntity.ok(user); } }
8.2 MyBatis框架 8.2.1 MyBatis使用 MyBatis :持久层框架。
MyBatis示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 @Mapper public interface UserMapper { @Select("SELECT * FROM users WHERE id = #{id}") User findById (Long id) ; @Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})") @Options(useGeneratedKeys = true, keyProperty = "id") void insert (User user) ; @Update("UPDATE users SET name = #{name} WHERE id = #{id}") void update (User user) ; @Delete("DELETE FROM users WHERE id = #{id}") void delete (Long id) ; }
9. 性能优化 9.1 代码优化 9.1.1 性能优化技巧 代码优化示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 public class CodeOptimization { public void useLocalVariable () { int localVar = 10 ; } public void reduceMethodCalls () { String str = "Hello" ; for (int i = 0 ; i < str.length(); i++) { } int len = str.length(); for (int i = 0 ; i < len; i++) { } } public void usePrimitiveType () { Integer sum = 0 ; for (int i = 0 ; i < 1000 ; i++) { sum += i; } int sum2 = 0 ; for (int i = 0 ; i < 1000 ; i++) { sum2 += i; } } public void useCache () { Map<String, Integer> cache = new HashMap <>(); public int calculate (String key) { if (cache.containsKey(key)) { return cache.get(key); } int result = expensiveCalculation(key); cache.put(key, result); return result; } } }
10. 总结 10.1 核心要点
基础扎实 :掌握Java基础语法和面向对象编程
集合熟练 :熟练使用各种集合框架
并发掌握 :理解多线程和并发编程
JVM理解 :理解JVM原理和性能调优
设计模式 :掌握常用设计模式
框架应用 :熟练使用主流框架
性能优化 :掌握性能优化技巧
10.2 学习路径
基础阶段 :Java语法、面向对象、集合框架
进阶阶段 :并发编程、JVM原理、设计模式
应用阶段 :框架使用、项目实战
精通阶段 :性能优化、架构设计
10.3 实践建议
多写代码 :通过实践加深理解
阅读源码 :阅读JDK和框架源码
性能测试 :进行性能测试和调优
项目实战 :通过项目积累经验
相关文章 :