簡體   English   中英

如何在Java中返回數組及其長度

[英]how to return an array and its length in java

我想從java中的方法返回數組及其長度,其中數組的類型為double,長度為integer,請幫助這個例子:

double ar={2.3,4.5,6.7};
 int len=ar.length();

現在我應該返回數組“ ar”和變量“ len”。 我試過這段代碼可以有人告訴我我需要在類中進行的修改,以便能夠返回所需的元素-:

 import java.util.List;
     public class Pair
     {
      private List<Double> array1;
    private List<Double> array2;
    public Pair(List<Double> array1, List<Double> array2)
    {
        this.array1 = array1;
        this.array2 = array2;

    }
    public List<Double> getArray1() { return array1; }
    public List<Double> getArray2() { return array2; }
}

如@Shekhar所述,數組長度已存儲在數組中。 另外,您提供的代碼不是您想要執行的操作。

嘗試

public class Pair {
    private double[] ar;
    private int length; 

    Pair(double[] ar) {
        this.ar[] = ar;
        this.length = ar.length;
    }

    public double[] getArray() {
        return this.ar;
    }

    public double getLength() {
        return this.length;
    }
}

只需單獨返回數組,然后在調用方法中獲取數組,或者如果您想使用數組屬性名稱獲取長度,則按如下方式獲取其長度length array.length()

public static void main(String[] args){
    Pair instance = new Pair();
    int length = instance.getArray().length;
    double[] arrayValue = instance.getArray();

}



public double[] getArray()     
{
    double[] st ={1.0,2.0};
    return st; 
}

如果要返回多個值,則可以創建另一個類並將其嵌入值(即整個數組和長度)中,然后返回類本身。

class temp
{
List<Double> array1;
int length;
}

public class Pair
{
private List<Double> array1;
private List<Double> array2;
temp t2 = new temp();
temp t1 = new temp();

public Pair(List<Double> array1, List<Double> array2)
{
t1.array1 = array1;
t1.length = array1.length;

t2.array1 = array2;
t2.length = array2.length;
}

public temp getArray1() { return t1; }
public temp getArray2() { return t2; }    
}

class temp
{
List<Double> array1;
int length;
}

public class Pair
{
private List<Double> array1;
private List<Double> array2;
temp t2 = new temp();
temp t1 = new temp();

public Pair(List<Double> array1, List<Double> array2)
{
     t1.array1 = array1;
     t1.length = array1.length;
     t2.array1 = array2;
     t2.length = array2.length;
}

public temp getArray1() { return t1; }
public temp getArray2() { return t2; }    
}


I dont know this code will work for sure or not but you can use the concept.
And other way is you can just declare the array itself globally. 


Thanks

您可以將其放在地圖中並返回地圖。

double [] arr = {2.3,1.2,4.5};

Map<String,Object> map = new HashMap<String,Object>();
map.put("array", arr);
map.put("arrayLength", arr.length);

return map;

您可以返回單個對象或數組。 如果您想要數組的長度,可以使用array.size(); 從函數中獲取數組后!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM