簡體   English   中英

如何在Java中返回類的數組

[英]How to return array of a class in Java

我正在嘗試將TestClass1[]包裝在TestClass ,為此我創建了一個TestClass 另一個類FunctionClass有一個方法將返回TestClass的數組。 我在Testclass定義了一些變量,一個是String ,另一個是類TestClass2 我將把TestClass2包裝在Testclass

Testclass2也有 2 個變量,一個是String ,一個是int 我想知道如何構造一個Testclass數組,其中應該包含相應的變量。

我有以下代碼。

public class Testclass {

private String attrName;
    private TestClass1 tc;
    private TestClass2 tc2;

Testclass(Testclass1[] tc1){

    for(int i=0; i<tc1.length; i++){
    tc = tc1[i];
    attrName = this.tc.name; 
    tc2 = new TestClass2 (this.tc.elements); //this.tc.elements will return an Array of SomeClass which is not implemented by me.
    }

}

/**
 * Returns the Name.
 */
public String getName()
{
    return attrName;
}

/**
 * Returns the Testclass2 Array
 */
public TestClass2[] getTestClass2(){

//What to do ??
}



 /**
 * Testclass2 which is inner class of TesTClass.
 */
 private class Testclass2 {

    private int value;
    private string attribute;
    private SomeClass some;

    TestClass2 (SomeClass[] someClass){

        for(int i=0; i<someClass.length; i++){
        some= someClass[i]; 
        this.value= some.value;
                    this.attributes = some.attribute;

        }
    }

            /**
             * Returns the Value.
             */
    public int getValue(){
        return value;
    }

            /**
             * Returns the Attribute.
             */
            public string getAttribute(){
        return attribute;
    }

Function類中的方法如下:

public Testclass[] getTestClass(){

 //What to do?

}

我發現你的構造函數很奇怪。 你會編碼甚至編譯嗎? 您想為 tc2 分配一個數組,但您沒有選擇它作為數組類型。 然后使用這個:

private TestClass2[] tc2;

然后在 getTestClass2 中,只需執行以下操作:

return tc2;

使類TestClass屬性成為數組。 如有必要,創建getter和 setter。 創建接受值或TestClass1並初始化TestClass2數組的構造函數初始值設定項。 TestClass2創建默認構造函數。

TestClass(TestClass1[] tc1, String attrName){

    tc = tc1;
    this.attrName = attrName; 
    if (tc != null) {
      tc2 = new TestClass2[tc.length];
      for(int i = 0; i< tc.length; i++) {
        TestClass2 t2c = new TestClass2(tc[i].getElements()); //this.tc.elements will   return an Array of SomeClass which is not implemented by me.
        tc2[i] = t2c;
      }
   }
}

/**
 * Returns the Testclass2 Array
 */
public TestClass2[] getTestClass2(){

  //What to do ?? 
  return tc2;
}

class TestClass2 {
   /**
    * Default constructor
    */ 
   TestClass2(){}

暫無
暫無

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

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