[英]How to add an object as a child of an object java
i'm stuck since hrs to a problem that regards adding an object as a child of another object: i have this class "Snapo" which contains the object Snapo, it is an array that contains the first index (m) which is an integer ,然后是列表 Snapo --> [m (s1 s2... sn)]。 現在我編寫了代碼來將一個只有“m”屬性的子元素添加到主 Snapo,但我不明白如何將 Snapo 添加到主 Snapo,例如:[8 ([5 ([7] [ 6])] [1 ([4] [3] [2])])] --> 其中“8”、“5”和“1”是“m”,其他數字是 Snapo 的列表
變量聲明:
private final static int SIZE = 100;
private int m;
public int[] arr = new int[SIZE];
private int top=0;
Snapo (int m) {
this.m = m;
arr[0] = this.m;
}
這是 class 的構造函數 ^
public void addChild (Snapo s) {
top++;
for (int i = top; i > 1; i--) {
arr[i] = arr[i - 1];
}
arr[1] = s.arr[0];
}
這是將單個數字添加到主 Snapo 的 addChild 方法 ^(頂部初始化為私有 int = 0)
我的程序適用於以下輸入:
Snapo s1 = new Snapo(1);
s1.addChild(new Snapo(2));
s1.addChild(new Snapo(3));
但它顯然沒有像這樣的輸入:
Snapo s3 = new Snapo(8);
s3.addChild(s1);
s3.addChild(s2);
也許這個例子可能有用
import java.util.ArrayList;
import java.util.List;
class TestAddC
{
public static void main(String args[])
{
TestAddC t= new TestAddC();
Snapo s1 = t.new Snapo("s1");
s1.addChild(t.new Snapo("s2"));
Snapo s3 = t.new Snapo("s3");
s1.addChild(s3);
Snapo s4 = t.new Snapo("s4");
s3.addChild(s4);
System.out.println(s1);
System.out.println(s3);
}
class Snapo
{
List<Snapo> listC= new ArrayList<Snapo>();
String name;
Snapo(String name)
{
this.name = name;
}
public void addChild(Snapo obj)
{
listC.add(obj);
}
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("parent="+this.name+"\n");
//only first level
listC.forEach(t->sb.append("child="+t.name+"\n"));
return sb.toString();
}
}
}
Output
parent=s1
child=s2
child=s3
parent=s3
child=s4
版本 2:使用 arrays
class TestAddC
{
public static void main(String args[])
{
TestAddC t= new TestAddC();
Snapo s1 = t.new Snapo("s1");
s1.addChild(t.new Snapo("s2"));
Snapo s3 = t.new Snapo("s3");
s1.addChild(s3);
Snapo s4 = t.new Snapo("s4");
s3.addChild(s4);
s3.addChild(s4);
s3.addChild(s4);
s3.addChild(s4);
s3.addChild(s1);
System.out.println(s1);
System.out.println(s3);
}
class Snapo
{
//add here up to how many children
Snapo[] listArr = new Snapo[3];
int counter = 0;
String name;
Snapo(String name)
{
this.name = name;
}
private int getNext()
{
System.out.println(counter);
return (counter<listArr.length)? counter++ :(listArr.length -1);
}
public void addChild(Snapo obj)
{
listArr[getNext()] = obj;
}
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("parent="+this.name+"\n");
//only first level
for(int i=0;i<listArr.length;i++)
{
if(listArr[i] instanceof Snapo )
{
sb.append("child="+listArr[i].name+"\n");
}
}
return sb.toString();
}
}
}
Output
parent=s1
child=s2
child=s3
//only 3 since arrsize is 3 (added 4, always last one have the last child)
parent=s3
child=s4
child=s4
child=s1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.