[英]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.