I want to build an array recursively I started this way and cant figure how to do it properly:
public class ConnectivityNode {
private Server server;
private ConnectivityNode parent;
private ArrayList<ConnectivityNode> children;
...
public Server[] getServerRoute(){
if(this.parent == null) { return null; }
return this.server + this.parent.getServerRoute(); //of course this isnt correct
}
}
The idea is to get an array of Servers
{ parent.parent.server1, parent.server2, server3 }
One option is to work with a List and create a helper function:
private void getServerRouter(List<Server> l) {
l.add(server);
if (parent != null) {
parent.getServerRouter(l)
}
}
public Server[] getServerRouter() {
List<Server> l = new ArrayList<>();
getServerRouter(l);
return l.toArray(new Server[l.size()]);
}
You might even consider returning the List from the public method (that might make more sense).
You will need an function with a parameter. So for example like this:
public void getServerRoute(Server actualServer){
children.add(actualServer);
if(actualServer.hasParent())
getServerRoute(actualServer.getParent());
}
As I do not know how you find the parent of a server I just assumed you have a function for that matter.
Use an ArrayList:
There are two ways to do this. If you have to return an array, you can use:
public Server[] getServerRoute()
{
if(this.parent == null)
{
return null;
}
ArrayList<Server> servers = new ArrayList<Server>();
servers.add(this.server);
servers.addAll(Arrays.asList(this.parent.getServerRoute()));
return servers.toArray(new Server[0]);
}
If it's okay to just return an ArrayList (which can trivially be converted into an array, just as we did above), it would be make the function simpler:
public ArrayList<Server> getServerRoute()
{
if(this.parent == null)
{
return null;
}
ArrayList<Server> servers = new ArrayList<Server>();
servers.add(this.server);
servers.addAll(this.parent.getServerRoute());
return servers;
}
if i understand you correcty, and you want to obtain route from current element to root element in your tree, it will be something like that:
public Server[] getServerRoute(){
List<Server> servers=new ArrayList<>();
walk(this,servers);
return servers.toArray(new Server[servers.size()]);
}
private static void walk(ConnectivityNode node,List<Server> servers)
{
servers.add(node.getServer());
if (node.getParent() != null)
{
walk(node.getParent(),servers);
}
}
Related
I programmed a Binary-Tree, now I am facing a problem during printing in order. When I call my printIO method, the printIOmethod calls another method which requires as parameter the root Node (as I print recursively) the method calls each time and passes the next node.
Is there any way to print the tree without 2 methods and no parameter in the main?
Idea:
make the temp Node static and don't use a parameter in the final print method. This didn't worked, as I got some Exceptions. Any idea?
Code snippet main:
BinList bl = new BinList();
bl.add(9);
bl.add(7);
...
bl.printIO();
Code snippet of the List Class:
public void printIO() {
print_in_order(root);
}
private void print_in_order(Node temp) {
if (temp != null) {
print_in_order(temp.left);
System.out.println(temp.data);
print_in_order(temp.right);
}
}
Instead of printing in the BinList class you should split the responsability between the BinList class and the Node class:
public class BinList {
private Node root = ...;
public void printInOrder() {
if (root != null) {
root.printInOrder();
}
}
}
public class Node {
private Node left, right;
private Object data;
public void printInOrder() {
if (left != null) {
left.printInOrder();
}
System.out.printl(data);
if (right != null) {
right.printInOrder();
}
}
}
I want to implement matryoshka dolls.
If you open one doll, there will be a smaller one inside until a massive doll that does not contain any another doll.
My try:
public static class Puppe{
int massive;
Puppe contains;
public static boolean massiveOrNot(Puppe doll) {
if(doll.massive==0) return true;
else return false;
}
public static Puppe exchangeDoll(Puppe doll) {
Puppe newDoll=new Puppe();
doll=newDoll;
return doll;
}
}
I´m completly new to classes.
How can I save dolls within other dolls and for example count how many dolls are inside of one doll?
Best regards
sop
First thing get rid of static for now, you will need more of this objects.
Then you have to think about is your object going to contain.
public class Puppe{
Puppe container;
public boolean isContaining() {
if(container != null) return true;
return false;
}
public void setDoll(Puppe smallerOne) {
container = smallerOne;
}
public Puppe getDoll() {
if(container != null)
return container;
return nullptr;
}
}
I have this kind of class
public class AImpl implements A {
private String variable = "init";
#Override
public A choice(A... choices) {
return this;
}
#Override
public A execute() {
variable = "execute";
return this;
}
}
I can use it like this (simple example)
new AImpl().choice(
new AImpl[] {
new AImpl().execute(),
new AImpl()
};
)
or like this (more complex example, with variable expected value)
new AImpl().choice( //variable == "init"
new AImpl[] {
new AImpl().execute(), //variable == "init". Set to "execute"
new AImpl().choice( //variable == "init"
new AImpl[] {
new AImpl() //variable == "init"
}
),
new AImpl().execute().choice( //variable == "init". Set to "execute"
new AImpl[] {
new AImpl(), //variable == "execute"
new AImpl() //variable == "execute"
}
),
};
)
What I'm trying to achieve
Each time there is a choice, I would like to propagate the last value of variable to each new instances. Here is graph version of the complex example where I encircled what I called propagation
What is my question
How can I propagate this variable to all the objects in the choices list before calling any other function (before calling execute in the simple example above, because this function uses (and can modify) this variable).
What I have tried
I can not do it using the constructor since I don't have a reference to the variable
public AImpl(String variable) {
this.variable = variable;
}
This code will not work because the variable will be set after all functions
#Override
public A choice(A... choices) {
for(A a : choices) {
a.setVariable(variable);
}
}
I tried with a Builder (eg set all the values and only create the instance at the end, from the choice function for example). But it make sense to chained the functions execute or choice (...execute().execute().choice()...). So the builder become difficult to create and can become really big.
I also tried to move the variable to a context class, but it is not working if in the choices I have another choice (case of the more complex example). Here is my current context class
public class Context {
private static Context instance = null;
private String variable;
private Context(){};
public String getVariable() {
return variable;
}
public void setVariable(String variable) {
this.variable = variable;
}
public static void set(String variable) {
if(Context.instance == null)
Context.instance = new Context();
Context.instance.setVariable(variable);
}
public static String get() {
if(Context.instance == null)
throw new NullPointerException();
return Context.instance.getVariable();
}
}
The problem is that new AImpl instances need to inherit the context of their "parent" AImple instance, i.e. the one on which choice() is called. You can't do that using the new operator. You should instead have a method that creates the instances with an inherited variable.
public A[] createChoices(int count, A optionalDefaultValues...) {
// return an array of clones of itself (possibly with adjusted defaults)
}
I finally found a working solution based on the Context approach (see What I have tried ?)
The main idea
There are two mains ideas. The first one is to replace (inside the context object) the single variable by a Stack of variables like this one
Stack<String> variables = new Stack<>();
I push the first variable in the first constructor and them I can access and modify it using pop/push function
String variable = Context.pop();
//Do something with variable
Context.push("anotherValue");
The second main idea is to duplicate the value on the top of the stack each time I create a new choice and to remove it at the end of each choice.
My code
Here is my code, if it can help someone else. I'm sure there is a lot of things to do to improve it, but it solved my original problem.
TestSo.java
public class TestSo {
#Test
public void testSo() {
AImpl.create().choice(
new ChoiceList()
.add(AChoice.create().execute())
.add(AChoice.create().choice(
new ChoiceList().add(AChoice.create())
))
.add(AChoice.create().execute().choice(
new ChoiceList()
.add(AChoice.create())
.add(AChoice.create())
))
);
}
}
A.java
public interface A {
A choice(ChoiceList choices);
A execute();
}
AAbstract.java
public class AAbstract implements A {
#Override
public A choice(ChoiceList choices) {
return this;
}
#Override
public A execute() {
String variable = Context.get();
//...
Context.set("execute");
return this;
}
}
AImpl.java
public class AImpl extends AAbstract {
private AImpl() {
Context.set("init");
}
public static AImpl create() {
return new AImpl();
}
}
AChoice.java
public class AChoice extends AAbstract {
private AChoice() {
Context.duplicate();
}
public static AChoice create() {
return new AChoice();
}
#Override
public AChoice choice(ChoiceList choices) {
super.choice(choices);
return this;
}
#Override
public AChoice execute() {
super.execute();
return this;
}
}
ChoiceList.java
public class ChoiceList {
private List<AChoice> choices = new ArrayList<>();
public ChoiceList add(AChoice choice) {
Context.remove();
choices.add(choice);
return this;
}
}
Context.java
public class Context {
private static Context instance = null;
private Stack<String> variables = new Stack<>();
private Context(){};
public String peek() {return variables.peek();}
public String pop() {return variables.pop();}
public void fork() {variables.push(variables.peek());}
public void push(String variable) {variables.push(variable);}
public static void set(String variable) {
if(Context.instance == null)
Context.instance = new Context();
Context.instance.push(variable);
}
public static String get() {
if(Context.instance == null)
throw new NullPointerException();
return Context.instance.pop();
}
public static void remove() {
if(Context.instance == null)
throw new NullPointerException();
Context.instance.pop();
}
public static void duplicate() {
if(Context.instance == null)
throw new NullPointerException();
Context.instance.fork();
}
public static String read() {
if(Context.instance == null)
throw new NullPointerException();
return Context.instance.peek();
}
}
I am working on a eclipse rcp project where I need to create a treeviewer out of TreeStructured Java object. Currently I have hardcorded the Java objects to create the structure and that is working fine. I need to create a method which calculates all the Parents and children object and form the tree structure. It should be a recursive method. I wrote a recursive method to generate a
tree structured java object. But it does not work properly.
I dont know where exactly the problem. request you to help on this. Please find the code below.
private FileParent getInput() {
FileParent root = new FileParent("Root");
FileParent A = new FileParent("A");
FileParent a1 = new FileParent("A1");
FileObject a11 = new FileObject("A11");
a1.addChild(a11);
FileObject a2 = new FileObject("A2");
A.addChild(a1);
A.addChild(a2);
FileParent b = new FileParent("B"); FileObject b1 = new
FileObject("B1"); FileObject b2 = new FileObject("B2");
b.addChild(b1); b.addChild(b2);
root.addChild(A);
// root.addChild(b);
return root;
}
My recursive method which is to traverse through all the Parents and children objects
and creates the tree structured object.
FileParent root1 = new FileParent("Root");
public FileParent getChildren(FileParent root) {
if (!root.hasChildren()) {
return root;
}
if (root != null && root.hasChildren()) {
FileObject[] children = root.getChildren();// size two
for (FileObject fileObject : children) { // 2 times
// here children will be the folders
if (fileObject instanceof FileParent) {
FileParent folder = (FileParent) fileObject;
// root1.setParent(folder.getParent());
// if (root1.getParent() != null) {
root1.addChild(folder);
// }
getChildren((FileParent) folder);
} else {
System.out.println("FileName: " + fileObject.getName());
// root1.setParent(fileObject.getParent());
// if (root1.getParent() != null) {
root1.addChild(fileObject);
// }
}
}
}
return root1;
}
public class FileObject {
private String name;
private FileParent parent;
public FileObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setParent(FileParent parent) {
this.parent = parent;
}
public FileParent getParent() {
return parent;
}
public String toString() {
return getName();
}
}
public class FileParent extends FileObject {
/**
*
*/
private List<FileObject> children;
public FileParent(String name) {
super(name);
children = new ArrayList<FileObject>();
}
public void addChild(FileObject child) {
// if (children.contains(child)) {
children.add(child);
child.setParent(this);
// }
}
public void removeChild(FileObject child) {
children.remove(child);
child.setParent(null);
}
public FileObject[] getChildren() {
return (FileObject[]) children.toArray(new FileObject[children.size()]);
}
public boolean hasChildren() {
return children.size() > 0;
}
}
In Swing there is interface TreeModel with default implementation Supposed to be used in JTree and generally not written the best way (like no generics), but can do the job.
There is one method in treeviewer.setInput(Object obj).If I pass getInput() as parameter It will work fine. But if I pass getChildren() which is my recursive method it does not work.
Do you mean you are calling treeviewer.setInput(foo.getChildren())? This is definitely wrong. Read this article: http://www.vogella.com/articles/EclipseJFaceTree/article.html.
Basically, you need to 1) implement ITreeContentProvider to provide the tree structure; 2) implement ILabelProvider to provide text and images; 3) call
treeViewer.setContentProvider(yourContentProvider);
treeViewer.setLabelProvider(yourLabelProvider);
treeviewer.setInput(new Object()); // or anything for which your content provider returns correct roots
I'm creating a (atypical)tree in Java that will be composed of three classes: node, branch and leaf
Each node stores the branches it is connected to in a HashSet. The branch is supposed to lead to a descendent node or a leaf, but I'm not sure how to code that. Would I just have two separate variables, one Node and one Leaf in the branch class, along with two sets of getters and setters, even though I will never use both? Is there a best practice in this regard?
I was thinking maybe make node and leaf subclasses of the same superclass, but they have absolutely nothing in common in terms of code(i.e. different variable types, functions, etc.).
EDIT:
Node references branches and
each Branch references a Node or a Leaf
I'd probably go with something like this:
interface BranchDestination {
boolean isLeaf();
}
class Node implements BranchDestination {
private Set branches;
public boolean isLeaf() {
return false;
}
...
}
class Leaf implements BranchDestination {
public boolean isLeaf() {
return true;
}
...
}
class Branch {
BranchDestination destination;
...
}
I do like the idea of defining an interface for the leaf / node classes, and implement that interface in each. I would define a simple function in that interface (syntax might be wrong below, but it's pseduo-ish code):
interface BranchItem {
public object[] GetVals();
}
public class Branch
{
public BranchItem item;
}
public class Leaf implements BranchItem
{
private object myVal = <your data here>;
public object[] GetVals() {
return new object[] { myVal };
}
}
public class Node implements BranchItem
{
private myBranches[] = <List of Branches>;
public object[] GetVals() {
object[] myArray = new object[];
foreach (BranchItem b in myBranches)
{
myArray.addTo(b.item.GetVals());
}
return myArray;
}
}
When traversing your node, simply iterate over the Branches and call GetVals().
The Leaf class will simply returns it's stored value.
The Node Class will recursively loop over it's branches, calling GetVals() on each and add it to it's own returned array.
This is but a simple implementation. If you want sort order, handle collisions or duplicate data, or anything of that nature it could get more complicated.
Make the Leaf class with the basic information.
Make the Branch class which holds references to Leafs.
Make the Node class which holds references to Brahces.
Then try look up Recursion and how to use it to make such constructs :)
Here is my go at it. Though not very elegant, it gets the job done.
Here is the Leaf class:
public class Leaf {
private String text;
public Leaf(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setString(String newString) {
text = newString;
}
#Override
public String toString() {
return text;
}
}
And here is the Branch class:
public class Branch<T> {
private String text;
private HashSet<T> list;
public Branch(String text) {
this.text = text;
list = new HashSet<>();
}
public String getText() {
return text;
}
public void setText(String newText) {
text = newText;
}
public HashSet<T> getHashSet() {
return list;
}
public void setHashSet(HashSet<T> newList) {
list = newList;
}
public String getAllLeaves() {
StringBuilder sb = new StringBuilder();
sb.append(text).append("\n");
for(T t : list) {
sb.append("\t\t");
sb.append(t.toString()).append("\n");
}
return sb.toString();
}
#Override
public String toString() {
return text;
}
}
Lastly the Node class:
public class Node<T> {
private String text;
private HashSet<T> list;
public Node(String text) {
this.text = text;
list = new HashSet<>();
}
public String getText() {
return text;
}
public void setText(String newText) {
text = newText;
}
public HashSet<T> getHashSet() {
return list;
}
public void setHashSet(HashSet<T> newList) {
list = newList;
}
}
Little test program to try it out:
public class TreeConstruct {
public static void main(String[] args) {
Leaf l1 = new Leaf("Leaf 1");
Leaf l2 = new Leaf("Leaf 2");
Leaf l3 = new Leaf("Leaf 3");
Leaf l4 = new Leaf("Leaf 4");
Branch<Leaf> b1 = new Branch("Branch 1");
Branch<Leaf> b2 = new Branch("Branch 2");
Node<Branch> n1 = new Node("Node 1");
b1.getHashSet().add(l1);
b1.getHashSet().add(l2);
b1.getHashSet().add(l3);
b2.getHashSet().add(l4);
n1.getHashSet().add(b1);
n1.getHashSet().add(b2);
System.out.println(printNodeTree(n1));
}
public static String printNodeTree(Node<Branch> n) {
StringBuilder sb = new StringBuilder();
sb.append(n.getText()).append("\n");
for(Branch b : n.getHashSet()) {
sb.append("\t");
sb.append(b.getAllLeaves());
}
return sb.toString();
}
}
The output will be:
Node 1
Branch 1
Leaf 1
Leaf 3
Leaf 2
Branch 2
Leaf 4
Hope this helps!