总结一下用Java做算法的常用类和方法

1. 数组操作 (Arrays)

  • Arrays.sort(array): 排序
  • Arrays.binarySearch(array, key): 二分查找
  • Arrays.fill(array, value): 填充值
  • Arrays.copyOf(array, newLength): 复制数组
  • Arrays.toString(array): 转换为字符串

2. 集合类 (Collection, List, Set, Map)

  • List (ArrayList) :
    • add(element), get(index), size(), contains(element), indexOf(element)
  • Set (HashSet) :
    • add(element), remove(element), contains(element), size()
  • Map (HashMap) :
    • put(key, value), get(key), containsKey(key), containsValue(value), size(), keySet(), values()

3. 字符串操作 (String)

  • length(), charAt(index), substring(start, end), startsWith(prefix), endsWith(suffix)
  • replace(old, new), toUpperCase(), toLowerCase(), trim(), split(regex)
  • StringBuilder 用于频繁拼接(第8点会详细讲)

4. 数学运算 (Math)

  • Math.max(a, b), Math.min(a, b), Math.abs(x), Math.sqrt(x), Math.pow(base, exp), Math.random()

5. 输入输出 (Scanner, BufferedReader)

  • Scanner: nextInt(), nextLine(), hasNext(), hasNextInt()
  • BufferedReader: readLine()

6. 排序和查找 (Collections)

  • Collections.sort(list), Collections.reverseOrder()
  • Collections.max(collection), Collections.min(collection)
  • Collections.binarySearch(list, key)

7. 数据结构

  • Stack : Deque<Integer> stack = new ArrayDeque<>(), push(), pop(), peek()
  • Queue : Queue<Integer> queue = new LinkedList<>(), offer(), poll(), peek()
  • PriorityQueue : 默认最小堆,offer(), poll(), peek()
  • Deque : ArrayDeque<>, 支持两端操作

8. StringBuilder (高效字符串操作):StringBuilder用于大量字符串拼接

  • append(): 追加字符串
  • insert(): 插入字符串
  • delete(): 删除字符
  • replace(): 替换字符
  • reverse(): 反转字符串
  • length(): 获取长度
  • toString(): 转换为String

9.正则表达式 (Pattern/Matcher):正则表达式用于模式匹配

  • Pattern.compile(pattern): 编译正则模式
  • matcher.find(): 查找匹配项
  • matcher.group(): 获取匹配的内容
  • String.split(regex): 按正则分割
  • String.replaceAll(regex, replacement): 正则替换
  • String.matches(regex): 完全匹配

10. 其他实用类

  • Integer.parseInt(string), Double.parseDouble(string)
  • String.valueOf(number)
  • System.currentTimeMillis() (计时)
java 复制代码
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 * Java算法常用类和方法总结
 */
public class AlgorithmUtilsSummaryComplete {
    
    public static void main(String[] args) {
        System.out.println("=== Java算法常用类和方法总结 - 完整版 ===\n");
        
        // 1. StringBuilder操作
        demonstrateStringBuilderOperations();
        
        // 2. 正则表达式
        demonstrateRegexOperations();
        
        // 3. 数组操作
        demonstrateArrayOperations();
        
        // 4. 集合类操作
        demonstrateCollectionOperations();
        
        // 5. 字符串操作
        demonstrateStringOperations();
        
        // 6. 数学运算
        demonstrateMathOperations();
        
        // 7. 输入输出
        demonstrateIOOperations();
        
        // 8. 排序
        demonstrateSorting();
        
        // 9. 查找
        demonstrateSearching();
        
        // 10. 数据结构
        demonstrateDataStructures();
    }
    
    // 1. StringBuilder操作
    public static void demonstrateStringBuilderOperations() {
        System.out.println("1. StringBuilder操作:");
        StringBuilder sb = new StringBuilder();
        
        // append: 追加
        sb.append("Hello");
        sb.append(" ");
        sb.append("World");
        System.out.println("追加后: " + sb.toString());
        
        // insert: 插入
        sb.insert(5, "_Java_");
        System.out.println("插入后: " + sb.toString());
        
        // delete: 删除
        sb.delete(5, 11); // 删除索引5到10的字符
        System.out.println("删除后: " + sb.toString());
        
        // replace: 替换
        sb.replace(0, 5, "Hi");
        System.out.println("替换后: " + sb.toString());
        
        // reverse: 反转
        sb.reverse();
        System.out.println("反转后: " + sb.toString());
        
        // length: 长度
        System.out.println("长度: " + sb.length());
        
        // capacity: 容量
        System.out.println("容量: " + sb.capacity());
        
        // charAt: 获取字符
        System.out.println("索引0的字符: " + sb.charAt(0));
        
        // substring: 子字符串
        System.out.println("子字符串: " + sb.substring(0, 2));
        
        // setCharAt: 设置字符
        sb.setCharAt(0, 'h');
        System.out.println("设置字符后: " + sb.toString());
        
        System.out.println();
    }
    
    // 2. 正则表达式
    public static void demonstrateRegexOperations() {
        System.out.println("2. 正则表达式操作:");
        
        // Pattern和Matcher
        String text = "我的电话是138-1234-5678,邮箱是user@example.com,身份证号是123456789012345678";
        
        // 匹配手机号
        String phonePattern = "\\d{3}-\\d{4}-\\d{4}";
        Pattern phoneRegex = Pattern.compile(phonePattern);
        Matcher phoneMatcher = phoneRegex.matcher(text);
        
        System.out.println("匹配手机号:");
        while (phoneMatcher.find()) {
            System.out.println("找到手机号: " + phoneMatcher.group());
        }
        
        // 匹配邮箱
        String emailPattern = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}";
        Pattern emailRegex = Pattern.compile(emailPattern);
        Matcher emailMatcher = emailRegex.matcher(text);
        
        System.out.println("匹配邮箱:");
        while (emailMatcher.find()) {
            System.out.println("找到邮箱: " + emailMatcher.group());
        }
        
        // 匹配身份证号
        String idPattern = "\\d{17}[\\dXx]";
        Pattern idRegex = Pattern.compile(idPattern);
        Matcher idMatcher = idRegex.matcher(text);
        
        System.out.println("匹配身份证:");
        while (idMatcher.find()) {
            System.out.println("找到身份证: " + idMatcher.group());
        }
        
        // 字符串的正则方法
        String sentence = "hello world 123 java 456";
        
        // split: 分割
        String[] parts = sentence.split("\\s+"); // 按空格分割
        System.out.println("分割结果: " + Arrays.toString(parts));
        
        // replaceAll: 替换所有匹配项
        String replaced = sentence.replaceAll("\\d+", "NUM"); // 将数字替换为NUM
        System.out.println("替换数字后: " + replaced);
        
        // replaceFirst: 替换第一个匹配项
        String replacedFirst = sentence.replaceAll("\\d+", "NUMBER");
        System.out.println("替换所有数字后: " + replacedFirst);
        
        // matches: 完全匹配
        String number = "12345";
        boolean isNumber = number.matches("\\d+");
        System.out.println("字符串'" + number + "'是否为纯数字: " + isNumber);
        
        // 常用正则模式
        System.out.println("\n常用正则模式:");
        System.out.println("- 数字: \\d+");
        System.out.println("- 字母: [a-zA-Z]+");
        System.out.println("- 字母数字: [a-zA-Z0-9]+");
        System.out.println("- 空白字符: \\s+");
        System.out.println("- 非空白字符: \\S+");
        System.out.println("- 任意字符: .*");
        System.out.println("- IP地址: ((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)");
        System.out.println("- URL: https?://[\\w.-]+(?:\\.[\\w\\.-]+)+[/\\w\\.-]*");
        
        System.out.println();
    }
    
    // 3. 数组操作
    public static void demonstrateArrayOperations() {
        System.out.println("3. 数组操作:");
        int[] arr = {3, 1, 4, 1, 5, 9, 2, 6};
        
        // 排序
        Arrays.sort(arr);
        System.out.println("排序后: " + Arrays.toString(arr));
        
        // 二分查找
        int index = Arrays.binarySearch(arr, 5);
        System.out.println("查找5的位置: " + index);
        
        // 填充
        int[] fillArr = new int[5];
        Arrays.fill(fillArr, 1);
        System.out.println("填充数组: " + Arrays.toString(fillArr));
        
        // 复制
        int[] copyArr = Arrays.copyOf(arr, arr.length);
        System.out.println("复制数组: " + Arrays.toString(copyArr));
        
        // 比较
        int[] arr2 = {1, 2, 3, 4, 5, 6, 9, 9};
        System.out.println("数组比较: " + Arrays.equals(arr, arr2));
        
        System.out.println();
    }
    
    // 4. 集合类操作
    public static void demonstrateCollectionOperations() {
        System.out.println("4. 集合类操作:");
        
        // List
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(1);
        System.out.println("List: " + list);
        System.out.println("List大小: " + list.size());
        System.out.println("是否包含1: " + list.contains(1));
        System.out.println("第一次出现1的位置: " + list.indexOf(1));
        System.out.println("最后一次出现1的位置: " + list.lastIndexOf(1));
        
        // Set
        Set<Integer> set = new HashSet<>();
        set.add(1);
        set.add(2);
        set.add(3);
        set.add(1); // 重复元素会被忽略
        System.out.println("Set: " + set);
        System.out.println("Set大小: " + set.size());
        System.out.println("Set是否包含2: " + set.contains(2));
        
        // Map
        Map<String, Integer> map = new HashMap<>();
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);
        System.out.println("Map: " + map);
        System.out.println("Map大小: " + map.size());
        System.out.println("key 'two'对应的值: " + map.get("two"));
        System.out.println("Map是否包含key 'four': " + map.containsKey("four"));
        System.out.println("Map是否包含value 2: " + map.containsValue(2));
        
        System.out.println();
    }
    
    // 5. 字符串操作
    public static void demonstrateStringOperations() {
        System.out.println("5. 字符串操作:");
        String str = "Hello World";
        
        System.out.println("原字符串: " + str);
        System.out.println("长度: " + str.length());
        System.out.println("字符数组: " + Arrays.toString(str.toCharArray()));
        System.out.println("子字符串: " + str.substring(0, 5));
        System.out.println("是否以'He'开头: " + str.startsWith("He"));
        System.out.println("是否以'ld'结尾: " + str.endsWith("ld"));
        System.out.println("替换: " + str.replace("World", "Java"));
        System.out.println("转大写: " + str.toUpperCase());
        System.out.println("转小写: " + str.toLowerCase());
        System.out.println("去掉首尾空格: " + "  Hello  ".trim());
        
        // 分割
        String[] parts = "a,b,c,d".split(",");
        System.out.println("分割结果: " + Arrays.toString(parts));
        
        System.out.println();
    }
    
    // 6. 数学运算
    public static void demonstrateMathOperations() {
        System.out.println("6. 数学运算:");
        
        System.out.println("绝对值: " + Math.abs(-10));
        System.out.println("最大值: " + Math.max(5, 10));
        System.out.println("最小值: " + Math.min(5, 10));
        System.out.println("向上取整: " + Math.ceil(4.3));
        System.out.println("向下取整: " + Math.floor(4.7));
        System.out.println("四舍五入: " + Math.round(4.5));
        System.out.println("平方根: " + Math.sqrt(16));
        System.out.println("幂运算: " + Math.pow(2, 3));
        System.out.println("随机数(0-1): " + Math.random());
        
        System.out.println();
    }
    
    // 7. 输入输出
    public static void demonstrateIOOperations() {
        System.out.println("7. 输入输出:");
        
        // Scanner用于读取输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("Scanner常用方法:");
        System.out.println("- next(): 读取下一个单词");
        System.out.println("- nextLine(): 读取整行");
        System.out.println("- nextInt(): 读取整数");
        System.out.println("- hasNext(): 判断是否还有输入");
        System.out.println("- hasNextInt(): 判断下一个是否为整数");
        
        // BufferedReader (更高效的输入)
        System.out.println("BufferedReader用于高效读取:");
        System.out.println("- readLine(): 读取一行");
        
        System.out.println();
    }
    
    // 8. 排序
    public static void demonstrateSorting() {
        System.out.println("8. 排序:");
        
        // 数组排序
        int[] arr = {5, 2, 8, 1, 9};
        Arrays.sort(arr);
        System.out.println("数组排序: " + Arrays.toString(arr));
        
        // 自定义排序 (降序)
        Integer[] arr2 = {5, 2, 8, 1, 9};
        Arrays.sort(arr2, Collections.reverseOrder());
        System.out.println("降序排序: " + Arrays.toString(arr2));
        
        // List排序
        List<Integer> list = Arrays.asList(5, 2, 8, 1, 9);
        Collections.sort(list);
        System.out.println("List排序: " + list);
        
        // 自定义排序规则
        List<String> words = Arrays.asList("apple", "hi", "banana");
        Collections.sort(words, (a, b) -> a.length() - b.length()); // 按长度排序
        System.out.println("按长度排序: " + words);
        
        System.out.println();
    }
    
    // 9. 查找
    public static void demonstrateSearching() {
        System.out.println("9. 查找:");
        
        int[] sortedArr = {1, 3, 5, 7, 9, 11, 13};
        int target = 7;
        int index = Arrays.binarySearch(sortedArr, target);
        System.out.println("二分查找 " + target + " 的位置: " + index);
        
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        int pos = Collections.binarySearch(list, 3);
        System.out.println("List中查找3的位置: " + pos);
        
        System.out.println("Collections.max: " + Collections.max(list));
        System.out.println("Collections.min: " + Collections.min(list));
        
        System.out.println();
    }
    
    // 10. 数据结构
    public static void demonstrateDataStructures() {
        System.out.println("10. 数据结构:");
        
        // Stack (用ArrayDeque模拟)
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println("Stack: " + stack + ", pop: " + stack.pop());
        
        // Queue
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(1);
        queue.offer(2);
        queue.offer(3);
        System.out.println("Queue: " + queue + ", poll: " + queue.poll());
        
        // PriorityQueue (最小堆)
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.offer(3);
        pq.offer(1);
        pq.offer(4);
        pq.offer(2);
        System.out.println("PriorityQueue: " + pq + ", poll: " + pq.poll());
        
        // Deque (双端队列)
        Deque<Integer> deque = new ArrayDeque<>();
        deque.offerFirst(1);
        deque.offerLast(2);
        deque.offerFirst(0);
        System.out.println("Deque: " + deque + ", removeFirst: " + deque.removeFirst() + ", removeLast: " + deque.removeLast());
        
        System.out.println();
    }
}
相关推荐
Elastic 中国社区官方博客10 分钟前
我们如何通过 70 多个拉取请求,将 OpenTelemetry Java agent 迁移到 invokedynamic
java·大数据·开发语言·elasticsearch·搜索引擎·全文检索·es
tyn18823 分钟前
记录本地安装nacos服务的方法及异常
java·开发语言
步行cgn1 小时前
Spring MVC 视图机制的核心接口与类
java·开发语言·后端·spring·mvc
y1su1 小时前
Leetcode 字符串模板
java·数据结构·算法·leetcode·职场和发展·动态规划
传奇开心果编程2 小时前
【Rust入门练中学】第5课:引用与借用
开发语言·rust·引用·编程语言理论·通用编程语言·借用
residual_fan2 小时前
船用柴油机动态机动工况故障诊断:控制感知仿射网络(CAAN)的技术实现
人工智能·算法·数据挖掘·数据分析
qetfw2 小时前
Bash 变量:export、位置参数与默认值展开验证
linux·开发语言·chrome·bash
电子云与长程纠缠2 小时前
UE5魂系游戏开发教程05
开发语言·学习·游戏·ui·ue5
其实防守也摸鱼2 小时前
Cylab在线靶场——CTF中的通用技能
linux·数据库·学习·算法·靶场·ctf·学习网络安全
cspttty2 小时前
2027风险管理岗准备路线:数学与应用数学如何补齐金融、SQL与Python
开发语言·python·金融