You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中构建支持实数与复数的Vector类?

线性代数库Vector类的返回类型问题

我正在用Java开发一个线性代数库,已经实现了Vector类和Complex类。原本的Vector类仅支持实数(double和int类型),通过data[]属性存储数值。现在我新增了cData[]和isComplex属性,初始化时通过不同构造函数设置isComplex为true,就用cData存储复数,目标是让用户能用同一个类无缝创建实数或复数向量。

但受Java特性限制,我遇到了核心问题:get()方法需要根据isComplex的值返回double(实数向量场景)或Complex(复数向量场景),而Java不允许一个方法拥有两种返回类型。我目前有几个思路:

  • 分别存储实部和虚部属性,但仍无法解决get()方法的返回类型问题;
  • 保留data[]、cData[]和isComplex属性,根据状态处理各类方法,但get()方法的返回类型问题依然存在;
  • 让Vector类仅接收Complex类型,但不确定这种设计对用户是否友好。

以下是当前的实现代码:

public class Vector {
   private double[] data;
   private Complex[] cData;
   private boolean isComplex = false;
   public final int length;

   public Vector(double[] vector) {
       this.data = vector;
       this.length = vector.length;
   }

   public Vector(String[] vector) throws ConstructFormatException {
       Complex[] array = new Complex[vector.length];
       for(int i = 0; i < vector.length; i++){
           array[i] = new Complex(vector[i]);
       }
       this.cData = array;
       this.isComplex = true;
       this.length = vector.length;
   }

   public void add(Vector vector) throws OperationUndefinedException{
       if(this.isComplex){
           // 复数向量加法逻辑待实现
       } else {
           MatrixOperation function = (d1, d2) -> {return d1 + d2;};
           applyOperation(vector, function);
       }
   }

   public double get(int index) throws OperationUndefinedException{
       if(index >= data.length){
           throw new OperationUndefinedException(INDEX_OUT_RANGE);
       }
       return data[index];
   }
}

内容的提问来源于stack exchange,提问作者Garmadon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 22:15:27