在Java中,对long值进行加法运算有多种API和方法,以下是详细整理:

1. 基础算术运算符

直接加法运算

long a = 100L;
long b = 200L;
long result = a + b;  // 300L

// 复合赋值
long c = 100L;
c += 200L;  // c = 300L

2. Math类API

Math.addExact() - 安全加法(推荐)

// 带溢出检查的加法
try {
    long result = Math.addExact(9223372036854775806L, 5L);
    System.out.println("结果: " + result);
} catch (ArithmeticException e) {
    System.out.println("加法溢出: " + e.getMessage());
}

其他Math类方法

// 无溢出检查
long sum1 = Math.addExact(100L, 200L);      // 300
long sum2 = Math.addExact(Long.MAX_VALUE, 1L);  // 抛出ArithmeticException

// 带符号的加法
long sum3 = Math.addExact(-100L, -200L);    // -300

3. BigInteger类(超大数值)

import java.math.BigInteger;

// 超过long范围的加法
BigInteger big1 = BigInteger.valueOf(Long.MAX_VALUE);
BigInteger big2 = BigInteger.valueOf(1000L);
BigInteger sum = big1.add(big2);

System.out.println("BigInteger加法: " + sum);

// 字符串构造
BigInteger big3 = new BigInteger("9223372036854775807");
BigInteger big4 = new BigInteger("1000");
BigInteger result = big3.add(big4);

4. AtomicLong类(线程安全)

import java.util.concurrent.atomic.AtomicLong;

AtomicLong atomicLong = new AtomicLong(100L);

// 多种加法方式
long result1 = atomicLong.addAndGet(50L);      // 先加后返回: 150
long result2 = atomicLong.getAndAdd(30L);      // 先返回后加: 150 (返回旧值)
long result3 = atomicLong.incrementAndGet();   // 加1: 181
long result4 = atomicLong.getAndIncrement();   // 先返回后加1: 181

// 自定义加法
long result5 = atomicLong.updateAndGet(x -> x + 100);

5. LongAdder类(高并发场景)

import java.util.concurrent.atomic.LongAdder;

LongAdder adder = new LongAdder();
adder.add(100L);      // 加100
adder.add(50L);       // 再加50
adder.increment();    // 加1

long sum = adder.sum();           // 获取当前总和
long sumThenReset = adder.sumThenReset(); // 获取并重置

6. Stream API(批量加法)

import java.util.Arrays;
import java.util.stream.LongStream;

// 数组求和
long[] numbers = {100L, 200L, 300L, 400L};
long sum = Arrays.stream(numbers).sum();  // 1000

// Stream操作
long result = LongStream.of(100, 200, 300)
    .reduce(0L, Long::sum);  // 600

// 并行计算
long parallelSum = LongStream.range(1L, 1000000L)
    .parallel()
    .sum();

7. OptionalLong类

import java.util.OptionalLong;

OptionalLong opt1 = OptionalLong.of(100L);
OptionalLong opt2 = OptionalLong.of(200L);

long sum = opt1.orElse(0) + opt2.orElse(0);  // 300

8. 工具类封装

安全加法工具类

public class LongMathUtils {
    
    /**
     * 安全加法,溢出时返回Long.MAX_VALUE或Long.MIN_VALUE
     */
    public static long safeAdd(long a, long b) {
        try {
            return Math.addExact(a, b);
        } catch (ArithmeticException e) {
            return a > 0 ? Long.MAX_VALUE : Long.MIN_VALUE;
        }
    }
    
    /**
     * 检查是否会溢出
     */
    public static boolean wouldOverflow(long a, long b) {
        try {
            Math.addExact(a, b);
            return false;
        } catch (ArithmeticException e) {
            return true;
        }
    }
    
    /**
     * 数组求和(防溢出)
     */
    public static long sum(long[] numbers) {
        long result = 0;
        for (long num : numbers) {
            try {
                result = Math.addExact(result, num);
            } catch (ArithmeticException e) {
                return num > 0 ? Long.MAX_VALUE : Long.MIN_VALUE;
            }
        }
        return result;
    }
}

9. 使用示例

public class LongAdditionExample {
    public static void main(String[] args) {
        // 1. 基本运算
        long simple = 100L + 200L;
        
        // 2. 安全加法
        long safe = Math.addExact(100L, 200L);
        
        // 3. 线程安全
        AtomicLong atomic = new AtomicLong(100L);
        atomic.addAndGet(200L);
        
        // 4. 大数值
        BigInteger big = BigInteger.valueOf(Long.MAX_VALUE)
            .add(BigInteger.valueOf(1000));
        
        // 5. 批量求和
        long[] arr = {100L, 200L, 300L};
        long sum = Arrays.stream(arr).sum();
        
        // 6. 高并发场景
        LongAdder adder = new LongAdder();
        adder.add(100L);
        adder.add(200L);
        
        System.out.println("简单加法: " + simple);
        System.out.println("安全加法: " + safe);
        System.out.println("原子加法: " + atomic.get());
        System.out.println("大数加法: " + big);
        System.out.println("数组求和: " + sum);
        System.out.println("LongAdder: " + adder.sum());
    }
}

选择建议:

  • 普通场景:直接用 + 运算符
  • 需要溢出检查Math.addExact()
  • 线程安全计数AtomicLongLongAdder
  • 超过long范围BigInteger
  • 批量求和Arrays.stream().sum()
  • 高并发累加LongAdder(性能优于AtomicLong)
Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐