I'm trying to create a 'skeletal' like system using class Bone and having the "primary" bone's children consist of all other bones that are connected.
public class Main {
public static void main(String[] args) {
Bone body = new Bone("primary", null);
Bone leftArm1 = new Bone("left_arm_1", body);
Bone leftArm2 = new Bone("left_arm_2", leftArm1);
Bone rightArm1 = new Bone("right_arm_1", body);
Bone rightArm2 = new Bone("right_arm_2", rightArm1);
List<Bone> bones = new ArrayList<Bone>();
for(Bone child : body.getChildren()) {
System.out.println(child.getName());
}
}
}
public class Bone {
private Bone parent = null;
private String name = null;
private List<Bone> children = new ArrayList<Bone>();
public Bone(String name, Bone parent) {
this.name = name;
this.parent = parent;
if(parent != null) {
parent.addChild(this);
}
}
public String getName() {
return this.name;
}
public Bone getParent() {
return this.parent;
}
public boolean hasParent() {
if(this.parent != null) {
return true;
} else {
return false;
}
}
public List<Bone> getChildren() {
return this.children;
}
public boolean hasChildren() {
if(this.children.isEmpty()) {
return false;
} else {
return true;
}
}
public void addChild(Bone child) {
this.children.add(child);
}
}
The current program is outputting...
left_arm_1
right_arm_1
when it should be outputting...
left_arm_1
left_arm_2
right_arm_1
right_arm_2
how would I make the program output the correct strings?
I would use recursion
public void printBones(Bone bone) {
if(bone == null) {
return;
}
List<Bone> children = bone.getChildren();
if(children != null && children.size() > 0) {
for(Bone bone : children) {
printBones(bone);
}
}
System.out.println(bone.getName());
}
Because body has only 2 children, the output is only left_arm_1 right_arm_1
If you want to print all children, you need to do it in recursion for all children of the children and so on.
Related
I have found few similar threads about infinity loop while trying save object as Json, but most of them are about java + jpa, and these solutions don't work for me. I would like to create tree structure of some data. There is class ProjectNode which got
private ArrayList<ProjectNode> children;
field. I'm pretty sure this one course the problem but its the main field in this structure, I can't ignore it. I have tested and I can convert object which has list with node which doesn't have children, but cant if any child got another children in the below code:
public class ProjectNode implements Comparable<ProjectNode>{
private String parent;
private String nodeName;
private String nodeHref;
private boolean hasChild;
private int td;
private ArrayList<ProjectNode> children;
public ProjectNode() {
super();
// TODO Auto-generated constructor stub
}
+ getters and setters
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(parser.getProjectFactory().get(12));
parser.getProjectFactory() returns list of ParentNodes (parent=null), I would like to convert 12 elements because there is a case where node has child and this child has child. Cause this error:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"]->java.util.ArrayList[31]->ProjectNode["children"])
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:734)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:119)
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serialize(IndexedListSerializer.java:79)
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serialize(IndexedListSerializer.java:18)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:727)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719)
EDIT:
Parser - parse project/hosts list from cacti:
public List<ProjectNode> getProjectFactory() throws FailingHttpStatusCodeException, MalformedURLException, IOException {
FileWriter fstream = new FileWriter("graphMap.txt");
BufferedWriter out = new BufferedWriter(fstream);
String [] hostInfo = null;
HtmlTableCell cel= (HtmlTableCell) page.getHtmlPage().getByXPath("/html/body/table/tbody/tr[5]/td[1]").get(0);
System.out.println(cel.getChildElementCount());
List<HtmlDivision> divs = cel.getByXPath(".//div");
System.out.println(divs.size());
//checks if list of host has been added to the project
ProjectTree projectTree = new ProjectTree();
Map<Integer,String> suppMap = new HashMap<Integer,String>();
for(HtmlDivision div : divs) {
List<DomNode> td = div.getByXPath(".//table/tbody/tr/td");
if(td.size()>2) {
ProjectNode pn = new ProjectNode(getNameSrc(td).split("#")[0],getNameSrc(td).split("#")[1],td.size());
hostInfo = getNameSrc(td).split("#");
if(pn.getTd()>3) {
if(!suppMap.get(pn.getTd()-1).isEmpty()) {
pn.setParent(suppMap.get(pn.getTd()-1));
}
if(suppMap.get(pn.getTd())!=null){
suppMap.remove(pn.getTd());
}
suppMap.put(pn.getTd(), pn.getNodeName());
projectTree.addNodeToTree(pn);
} else {
projectTree.addNodeToTree(pn);
suppMap.put(pn.getTd(), pn.getNodeName());
//out.write(pn.toString()+"\n");
}
}
}
ArrayList<ProjectNode> pns = projectTree.getNodeList();
Collections.sort(pns, Comparator.comparing(ProjectNode::getTd));
Collections.reverse(pns);
projectTree.setNodeList(pns);
List<ProjectNode> finalList = new ArrayList<ProjectNode>();
for(ProjectNode pn :pns ) {
if(pn.getTd()==3) {
finalList.add(pn);
}else {
projectTree.addToParent(pn);
}
}
Collections.reverse(finalList);
for(ProjectNode pn : finalList) {
Collections.sort(pn.getChildren());
}
out.write(finalList.get(12).getChildren().get(4).getChildren().toString());
out.close();
System.out.println(finalList.size());
return finalList;
}
ProjectTree class
public class ProjectTree {
private ProjectNode rootNode;
private ArrayList<ProjectNode> NodeList;
public ProjectTree() {
super();
this.NodeList = new ArrayList<ProjectNode>();
}
public ProjectTree(ProjectNode rootNode, ArrayList<ProjectNode> nodeList) {
super();
this.rootNode = rootNode;
NodeList = nodeList;
}
public ArrayList<ProjectNode> groupHosts(){
return this.NodeList;
}
public void addToParent(ProjectNode pn) {
for(ProjectNode pnA :this.NodeList) {
if(pnA.getNodeName().equals(pn.getParent())) {
if(pnA.getChildren()!=null && pnA.getChildren().size()!=0) {
pnA.sortChildren();
}
pnA.addChlild(pn);
}
}
}
public ProjectNode getRootNode() {
return rootNode;
}
public void setRootNode(ProjectNode rootNode) {
this.rootNode = rootNode;
}
public ArrayList<ProjectNode> getNodeList() {
return NodeList;
}
public void setNodeList(ArrayList<ProjectNode> nodeList) {
NodeList = nodeList;
}
}
ProjectNode.class
public class ProjectNode implements Comparable<ProjectNode>{
private String parent;
private String nodeName;
private String nodeHref;
private boolean hasChild;
private int td;
private ArrayList<ProjectNode> children;
public ProjectNode() {
super();
// TODO Auto-generated constructor stub
}
public ProjectNode( String nodeName, String nodeHref, int td) {
super();
this.nodeName = nodeName;
this.nodeHref = nodeHref;
this.hasChild =false;
this.td=td;
}
public void addChlild(ProjectNode pn) {
if(children!=null) {
this.children.add(pn);
}else {
this.children = new ArrayList<ProjectNode>();
this.children.add(pn);
}
}
public List<ProjectNode> getChildren() {
return children;
}
public void sortChildren() {
Collections.sort(this.getChildren());;
//Collections.sort(this.getChildren(), Comparator.comparing(ProjectNode::getNodeName));
//System.out.println(this.children.toString());
}
public void setChildren(ArrayList<ProjectNode> children) {
this.children = children;
}
public int getTd() {
return td;
}
public void setTd(int td) {
this.td = td;
}
public boolean isHasChild() {
return hasChild;
}
public void setHasChild(boolean hasChild) {
this.hasChild = hasChild;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public String getNodeHref() {
return nodeHref;
}
public void setNodeHref(String nodeHref) {
this.nodeHref = nodeHref;
}
#Override
public String toString() {
return "ProjectNode [parent=" + parent + ", nodeName=" + nodeName + ", nodeHref=" + nodeHref + ", hasChild="
+ hasChild + ", td=" + td + ", children=" +"]";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((children == null) ? 0 : children.hashCode());
result = prime * result + (hasChild ? 1231 : 1237);
result = prime * result + ((nodeHref == null) ? 0 : nodeHref.hashCode());
result = prime * result + ((nodeName == null) ? 0 : nodeName.hashCode());
result = prime * result + ((parent == null) ? 0 : parent.hashCode());
result = prime * result + td;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProjectNode other = (ProjectNode) obj;
if (children == null) {
if (other.children != null)
return false;
} else if (!children.equals(other.children))
return false;
if (hasChild != other.hasChild)
return false;
if (nodeHref == null) {
if (other.nodeHref != null)
return false;
} else if (!nodeHref.equals(other.nodeHref))
return false;
if (nodeName == null) {
if (other.nodeName != null)
return false;
} else if (!nodeName.equals(other.nodeName))
return false;
if (parent == null) {
if (other.parent != null)
return false;
} else if (!parent.equals(other.parent))
return false;
if (td != other.td)
return false;
return true;
}
#Override
public int compareTo(ProjectNode o) {
// TODO Auto-generated method stub
return nodeName.compareTo(o.getNodeName());
}
}
I would use recursive to groupd all nodes in corect place but i had same error (with stackoverflow) so i had to use work around which is addToParent() function.
I have managed it by breaking loop when parent of my node have been found. I made it just for performance because before even if parent has been found loop was checking all elements anyway so i added break, and it works.. Not sure why..
Code below:
public void group() {
int td = this.highestTd;
while (td > 2) {
List<ProjectNode> toRemove = new ArrayList<ProjectNode>();
for (ProjectNode pnA : this.NodeList) {
if(pnA.getTd()==3) {
pnA.setParent("root");
}
if (pnA.getTd() == td) {
for (ProjectNode pnB : this.NodeList) {
System.out.println(pnB.toString());
if (pnA.getParent()!=null && pnA.getParent().equals(pnB.getNodeName())) {
System.out.println("Dodaje "+pnA.getNodeName() + " Do "+pnB.getNodeName());
pnB.addChlild(pnA);
toRemove.add(pnA);
break;
}
}
}
}
td--;
this.NodeList.removeAll(toRemove);
}
}
How do I use DOTGenerator to convert a parse tree to DOT/graphviz format in ANTLR4?
I found this related question but the only answer uses TreeViewer to display the tree in a JPanel and that's not what I'm after. This other question is exacly what I need but it didn't get answered. Everything else I stumbled upon relates to DOTTreeGenerator from ANTLR3 and it's not helpful.
I'm using Java with the ANTLR4 plugin for IntelliJ.
I have a small project that has all kind of utility methods w.r.t. ANTLR4 grammar debugging/testing. I haven't found the time to provide it of some proper documentation so that I can put it on Github. But here's a part of it responsible for creating a DOT file from a grammar.
Stick it all in a single file called Main.java (and of course generate the lexer and parser for Expression.g4), and you will see a DOT string being printed to your console:
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import java.util.*;
public class Main {
public static void main(String[] args) {
/*
// Expression.g4
grammar Expression;
expression
: '-' expression
| expression ('*' | '/') expression
| expression ('+' | '-') expression
| '(' expression ')'
| NUMBER
| VARIABLE
;
NUMBER
: [0-9]+ ( '.' [0-9]+ )?
;
VARIABLE
: [a-zA-Z] [a-zA-Z0-9]+
;
SPACE
: [ \t\r\n] -> skip
;
*/
String source = "3 + 42 * (PI - 3.14159)";
ExpressionLexer lexer = new ExpressionLexer(CharStreams.fromString(source));
ExpressionParser parser = new ExpressionParser(new CommonTokenStream(lexer));
SimpleTree tree = new SimpleTree.Builder()
.withParser(parser)
.withParseTree(parser.expression())
.withDisplaySymbolicName(false)
.build();
DotOptions options = new DotOptions.Builder()
.withParameters(" labelloc=\"t\";\n label=\"Expression Tree\";\n\n")
.withLexerRuleShape("circle")
.build();
System.out.println(new DotTreeRepresentation().display(tree, options));
}
}
class DotTreeRepresentation {
public String display(SimpleTree tree) {
return display(tree, DotOptions.DEFAULT);
}
public String display(SimpleTree tree, DotOptions options) {
return display(new InOrderTraversal().traverse(tree), options);
}
public String display(List<SimpleTree.Node> nodes, DotOptions options) {
StringBuilder builder = new StringBuilder("graph tree {\n\n");
Map<SimpleTree.Node, String> nodeNameMap = new HashMap<>();
int nodeCount = 0;
if (options.parameters != null) {
builder.append(options.parameters);
}
for (SimpleTree.Node node : nodes) {
nodeCount++;
String nodeName = String.format("node_%s", nodeCount);
nodeNameMap.put(node, nodeName);
builder.append(String.format(" %s [label=\"%s\", shape=%s];\n",
nodeName,
node.getLabel().replace("\"", "\\\""),
node.isTokenNode() ? options.lexerRuleShape : options.parserRuleShape));
}
builder.append("\n");
for (SimpleTree.Node node : nodes) {
String name = nodeNameMap.get(node);
for (SimpleTree.Node child : node.getChildren()) {
String childName = nodeNameMap.get(child);
builder.append(" ").append(name).append(" -- ").append(childName).append("\n");
}
}
return builder.append("}\n").toString();
}
}
class InOrderTraversal {
public List<SimpleTree.Node> traverse(SimpleTree tree) {
if (tree == null)
throw new IllegalArgumentException("tree == null");
List<SimpleTree.Node> nodes = new ArrayList<>();
traverse(tree.root, nodes);
return nodes;
}
private void traverse(SimpleTree.Node node, List<SimpleTree.Node> nodes) {
if (node.hasChildren()) {
traverse(node.getChildren().get(0), nodes);
}
nodes.add(node);
for (int i = 1; i < node.getChildCount(); i++) {
traverse(node.getChild(i), nodes);
}
}
}
class DotOptions {
public static final DotOptions DEFAULT = new DotOptions.Builder().build();
public static final String DEFAULT_PARAMETERS = null;
public static final String DEFAULT_LEXER_RULE_SHAPE = "box";
public static final String DEFAULT_PARSER_RULE_SHAPE = "ellipse";
public static class Builder {
private String parameters = DEFAULT_PARAMETERS;
private String lexerRuleShape = DEFAULT_LEXER_RULE_SHAPE;
private String parserRuleShape = DEFAULT_PARSER_RULE_SHAPE;
public DotOptions.Builder withParameters(String parameters) {
this.parameters = parameters;
return this;
}
public DotOptions.Builder withLexerRuleShape(String lexerRuleShape) {
this.lexerRuleShape = lexerRuleShape;
return this;
}
public DotOptions.Builder withParserRuleShape(String parserRuleShape) {
this.parserRuleShape = parserRuleShape;
return this;
}
public DotOptions build() {
if (lexerRuleShape == null)
throw new IllegalStateException("lexerRuleShape == null");
if (parserRuleShape == null)
throw new IllegalStateException("parserRuleShape == null");
return new DotOptions(parameters, lexerRuleShape, parserRuleShape);
}
}
public final String parameters;
public final String lexerRuleShape;
public final String parserRuleShape;
private DotOptions(String parameters, String lexerRuleShape, String parserRuleShape) {
this.parameters = parameters;
this.lexerRuleShape = lexerRuleShape;
this.parserRuleShape = parserRuleShape;
}
}
class SimpleTree {
public static class Builder {
private Parser parser = null;
private ParseTree parseTree = null;
private Set<Integer> ignoredTokenTypes = new HashSet<>();
private boolean displaySymbolicName = true;
public SimpleTree build() {
if (parser == null) {
throw new IllegalStateException("parser == null");
}
if (parseTree == null) {
throw new IllegalStateException("parseTree == null");
}
return new SimpleTree(parser, parseTree, ignoredTokenTypes, displaySymbolicName);
}
public SimpleTree.Builder withParser(Parser parser) {
this.parser = parser;
return this;
}
public SimpleTree.Builder withParseTree(ParseTree parseTree) {
this.parseTree = parseTree;
return this;
}
public SimpleTree.Builder withIgnoredTokenTypes(Integer... ignoredTokenTypes) {
this.ignoredTokenTypes = new HashSet<>(Arrays.asList(ignoredTokenTypes));
return this;
}
public SimpleTree.Builder withDisplaySymbolicName(boolean displaySymbolicName) {
this.displaySymbolicName = displaySymbolicName;
return this;
}
}
public final SimpleTree.Node root;
private SimpleTree(Parser parser, ParseTree parseTree, Set<Integer> ignoredTokenTypes, boolean displaySymbolicName) {
this.root = new SimpleTree.Node(parser, parseTree, ignoredTokenTypes, displaySymbolicName);
}
public SimpleTree(SimpleTree.Node root) {
if (root == null)
throw new IllegalArgumentException("root == null");
this.root = root;
}
public SimpleTree copy() {
return new SimpleTree(root.copy());
}
public String toLispTree() {
StringBuilder builder = new StringBuilder();
toLispTree(this.root, builder);
return builder.toString().trim();
}
private void toLispTree(SimpleTree.Node node, StringBuilder builder) {
if (node.isLeaf()) {
builder.append(node.getLabel()).append(" ");
}
else {
builder.append("(").append(node.label).append(" ");
for (SimpleTree.Node child : node.children) {
toLispTree(child, builder);
}
builder.append(") ");
}
}
#Override
public String toString() {
return String.format("%s", this.root);
}
public static class Node {
protected String label;
protected int level;
protected boolean isTokenNode;
protected List<SimpleTree.Node> children;
Node(Parser parser, ParseTree parseTree, Set<Integer> ignoredTokenTypes, boolean displaySymbolicName) {
this(parser.getRuleNames()[((RuleContext)parseTree).getRuleIndex()], 0, false);
traverse(parseTree, this, parser, ignoredTokenTypes, displaySymbolicName);
}
public Node(String label, int level, boolean isTokenNode) {
this.label = label;
this.level = level;
this.isTokenNode = isTokenNode;
this.children = new ArrayList<>();
}
public void replaceWith(SimpleTree.Node node) {
this.label = node.label;
this.level = node.level;
this.isTokenNode = node.isTokenNode;
this.children.remove(node);
this.children.addAll(node.children);
}
public SimpleTree.Node copy() {
SimpleTree.Node copy = new SimpleTree.Node(this.label, this.level, this.isTokenNode);
for (SimpleTree.Node child : this.children) {
copy.children.add(child.copy());
}
return copy;
}
public void normalizeLevels(int level) {
this.level = level;
for (SimpleTree.Node child : children) {
child.normalizeLevels(level + 1);
}
}
public boolean hasChildren() {
return !children.isEmpty();
}
public boolean isLeaf() {
return !hasChildren();
}
public int getChildCount() {
return children.size();
}
public SimpleTree.Node getChild(int index) {
return children.get(index);
}
public int getLevel() {
return level;
}
public String getLabel() {
return label;
}
public boolean isTokenNode() {
return isTokenNode;
}
public List<SimpleTree.Node> getChildren() {
return new ArrayList<>(children);
}
private void traverse(ParseTree parseTree, SimpleTree.Node parent, Parser parser, Set<Integer> ignoredTokenTypes, boolean displaySymbolicName) {
List<SimpleTree.ParseTreeParent> todo = new ArrayList<>();
for (int i = 0; i < parseTree.getChildCount(); i++) {
ParseTree child = parseTree.getChild(i);
if (child.getPayload() instanceof CommonToken) {
CommonToken token = (CommonToken) child.getPayload();
if (!ignoredTokenTypes.contains(token.getType())) {
String tempText = displaySymbolicName ?
String.format("%s: '%s'",
parser.getVocabulary().getSymbolicName(token.getType()),
token.getText()
.replace("\r", "\\r")
.replace("\n", "\\n")
.replace("\t", "\\t")
.replace("'", "\\'")) :
String.format("%s",
token.getText()
.replace("\r", "\\r")
.replace("\n", "\\n")
.replace("\t", "\\t"));
if (parent.label == null) {
parent.label = tempText;
}
else {
parent.children.add(new SimpleTree.Node(tempText, parent.level + 1, true));
}
}
}
else {
SimpleTree.Node node = new SimpleTree.Node(parser.getRuleNames()[((RuleContext)child).getRuleIndex()], parent.level + 1, false);
parent.children.add(node);
todo.add(new SimpleTree.ParseTreeParent(child, node));
}
}
for (SimpleTree.ParseTreeParent wrapper : todo) {
traverse(wrapper.parseTree, wrapper.parent, parser, ignoredTokenTypes, displaySymbolicName);
}
}
#Override
public String toString() {
return String.format("{label=%s, level=%s, isTokenNode=%s, children=%s}", label, level, isTokenNode, children);
}
}
private static class ParseTreeParent {
final ParseTree parseTree;
final SimpleTree.Node parent;
private ParseTreeParent(ParseTree parseTree, SimpleTree.Node parent) {
this.parseTree = parseTree;
this.parent = parent;
}
}
}
And if you paste the output in a DOT viewer, you will get this:
You may also want to look at alternatives. DOT graphs aren't the pretties among possible graph representations. Maybe you like an svg graph instead? If so have a look at the ANTLR4 grammar extension for Visual Studio Code, which generates and exports an svg graphic with the click of a mouse button (and you can style that with own CSS code).
I defined classes Graph containing GraphNode as follows, my intention for declaring N is to compare 2 GraphNode objects using generics.
The question is how shall I instantiate the Graph which is recursively bound.
error while declaring as below.
Graph<Integer,Comparable<GraphNode>> graph = new Graph<>();
Bound mismatch: The type Comparable<GraphNode> is not a valid substitute for the bounded parameter <N extends Comparable<GraphNode<T,N>>> of the type Graph<T,N>
public class Graph<T, N extends Comparable<GraphNode<T, N>>> {
private N root;
private Class<N> clazz;
Graph(Class<N> clazz) {
this.clazz = clazz;
}
public N getInstance() {
try {
return clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
#SuppressWarnings("unchecked")
public void insert(T d, N n) {
if (root == null && n == null)
root = getInstance();
if (root == null)
root = n;
N node = root;
while (node != null) {
if (node.equals(n)) {
N newNode = getInstance();
((GraphNode<T, N>) newNode).setAdjNode(newNode);
}
}
}
}
public class GraphNode<T, N extends Comparable<GraphNode<T, N>>> implements Comparable<N> {
private T data;
private LinkedHashSet<N> adjNodes = new LinkedHashSet<>();
GraphNode() {
data = null;
}
GraphNode(T d) {
setData(d);
}
public void setAdjNode(N n) {
adjNodes.add(n);
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
#Override
public int hashCode() {
return data.hashCode();
}
#Override
public boolean equals(Object obj) {
if (obj instanceof GraphNode<?, ?>) {
return ((GraphNode<?, ?>) obj).getData() == this.getData();
}
return false;
}
#Override
public String toString() {
return data + "";
}
#Override
public int compareTo(N o) {
return this.compareTo(o);
}
}
This solved my above problem
public class Graph<T extends Comparable<T>> {
private GraphNode<T> root;
public void insert(T d, GraphNode<T> n) {
if (root == null && n == null)
root = new GraphNode<T>(d);
if (root == null)
root = n;
GraphNode<T> node = root;
Queue<GraphNode<T>> queue = new ConcurrentLinkedQueue<>();
queue.add(root);
while (!queue.isEmpty()) {
node = queue.poll();
node.setNodeColor(color.BLACK);
if (node.equals(n)) {
GraphNode<T> newNode = new GraphNode<T>(d);
((GraphNode<T>) newNode).setAdjNode(newNode);
} else {
queue.addAll(node.getUnexploredAdjNodes());
}
}
}
}
public class GraphNode<T extends Comparable<T>> implements Comparable<GraphNode<T>> {
enum color {
WHITE, GREY, BLACK
};
private T data;
private color nodeColor = color.WHITE;
private LinkedHashSet<GraphNode<T>> adjNodes = new LinkedHashSet<>();
GraphNode() {
data = null;
}
GraphNode(T d) {
setData(d);
}
public void setAdjNode(GraphNode<T> n) {
adjNodes.add(n);
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public LinkedHashSet<GraphNode<T>> getAdjNodes() {
return adjNodes;
}
public LinkedHashSet<GraphNode<T>> getUnexploredAdjNodes() {
LinkedHashSet<GraphNode<T>> n = new LinkedHashSet<>();
for (GraphNode<T> node : adjNodes) {
if (node.getNodeColor() == color.WHITE)
n.add(node);
}
return n;
}
public color getNodeColor() {
return nodeColor;
}
public void setNodeColor(color nodeColor) {
this.nodeColor = nodeColor;
}
#Override
public int hashCode() {
return data.hashCode();
}
#Override
public boolean equals(Object obj) {
if (obj instanceof GraphNode<?>) {
return ((GraphNode<?>) obj).getData() == this.getData();
}
return false;
}
#Override
public int compareTo(GraphNode<T> o) {
return data.compareTo(o.data);
}
#Override
public String toString() {
return data + "";
}
}
Graph<Integer> graph = new Graph<>();
I am beginning to study Java. As an assigment I have to implement a doubly linked list with given interfaces which i included in the code.
My method insertAtTheEnd() seems not to work properly, since I have the value null on elements after inserting several ones.
I checked similar questions on that topic and tried to apply the answers to my problem, but could not get any further. So any help is appreciated how i can setup this method to make it work.
Thanks!
public interface IValueElement
{
public String getName();
public void setName(String paramName);
public int getValue();
public void setValue(int paramValue);
}
public interface IListElement
{
public IValueElement getValueElement();
public void setValueElement(IValueElement value);
public IListElement getPredecessor();
public void setPredecessor(IListElement predecessor);
public IListElement getSuccessor();
public void setSuccessor(IListElement successor);
}
public interface IList
{
public IListElement getHead();
public void insertAtTheEnd(IValueElement value);
//...
}
public class List implements IList
{
public List()
{
if (head == null)
{
head = new ListElement(null);
}
else
{
return;
}
}
private IListElement head;
public IListElement getHead()
{
return head;
}
public void insertAtTheEnd(IValueElement value)
{
if (head.getSuccessor() != null)
{
IListElement l = head;
while (l.getSuccessor() != null)
l = l.getSuccessor();
IListElement q = new ListElement(value);
l.setPredecessor(q);
}
else
{
IListElement q = new ListElement(value);
q.setPredecessor(head);
q.setSuccessor(null);
head.setSuccessor(q);
head.setPredecessor(q);
}
}
}
Additionally here are my implementations of ValueElement and ListElement:
//ListElement.java
public class ListElement implements IListElement
{
public ListElement(IValueElement value)
{
this.valueElement = checkValueElementAttribute(value);
}
private IValueElement checkValueElementAttribute(IValueElement value)
{
return (value == null) ? new ValueElement(null, 0) : value;
}
private IValueElement valueElement;
public IValueElement getValueElement()
{
return this.valueElement;
}
public void setValueElement(IValueElement value)
{
if (value != null)
{
this.valueElement = value;
}
}
private IListElement predecessor;
public IListElement getPredecessor()
{
return this.predecessor;
}
public void setPredecessor(IListElement predecessor)
{
this.predecessor = predecessor;
}
private IListElement successor;
public IListElement getSuccessor()
{
return this.successor;
}
public void setSuccessor(IListElement successor)
{
this.successor = successor;
}
}
// ValueElement.java
public class ValueElement implements IValueElement
{
private String name;
public String getName()
{
return this.name;
}
public void setName(String paramName)
{
if (paramName != null)
{
this.name = paramName;
}
}
public ValueElement(String name, int value)
{
if (name == null || name.equals(""))
{
name = "default";
}
else
{
this.name = name;
}
this.value = value;
}
private int value;
public int getValue()
{
return this.value;
}
public void setValue(int paramValue)
{
if (paramValue != 0)
{
this.value = paramValue;
}
}
public String toString()
{
return "Name: " + this.name + " - Value: " + this.value;
}
}
please provide the complete code so that we can run that and help you as of now we can only think of these problems:
1) you might not have called setValueElement on those nodes
2)your else block contains setting of both predecessor and successor to the same element so its a definite wrong line of code
shouldn't this be your code
public void insertAtTheEnd(IValueElement value)
{
if (head.getSuccessor() != null)
{
IListElement l = head;
while (l.getSuccessor() != null)
l = l.getSuccessor();
IListElement q = new ListElement(value);
l.setSuccessor(q);
}
else
{
IListElement q = new ListElement(value);
q.setPredecessor(head);
q.setSuccessor(null);
head.setSuccessor(q);
}
}
Have implementations of IValueElement and IListElement been provided for you, or are they something that you must also implement? From the code you have provided I cannot see implementations for them.
Regarding your method insertAtTheEnd, it looks like you have mostly the right idea, but maybe you could improve on it.
At the end of the if block, you set l's predecessor to q. I think that might be the wrong way round. l at that point is the last element in the list, having walked along the chain of successors until there is no more, it seems to me that the new element (q) should now be added as a successor to l NOT a predecessor.
In addition, I think q would need to have it's predecessor set to l.
In your else block you correctly set q's predecessor and successor, and correctly set head's successor, however, why do you set head's predecessor to q? That would make q both a successor and predecessor to head. I think you should just remove that last setPredecessor call.
all guys
I am developing with Flex + java + hibernate in one project.
I am trying to add one more advanceddatagridcolumn in flex AdavanedDataGrid control.
Actually it work very well but only except I added column’s data.
I have no idea what should I do to make it out
I am telling work flow.
At first call select method in DeliveryService.class through the RemoteObject and then call
DeliveryMgr.class for call business work. After get return list type return value it pass to presentation class to setting all of the selected return value.
I can print trace log what I added column’s data in DeliveryPt.class but it cannot return to flex area.
Strange thing is I can check out value of what I want to show data in DeliveryPt.class but it does not show up in AdvanedDataGridColumn of Flex.
Thank you for reading in Advance.
DeliverService.java
public DeliveryService() {
}public List<DeliveryPt> selectMaterialForReReceiptDelivery(String referenceNo,String team,String buyerCode,Integer kind,String sessionId){
List<DeliveryPt> rtnList = new ArrayList<DeliveryPt>();
List<Delivery> tmpList = new ArrayList<Delivery>();
ApplicationContext ac = CommonResource.getAppcontext();
DeliveryMgr dmgr = (DeliveryMgr)ac.getBean("DeliveryMgr");
tmpList = dmgr.selectMaterialForReReceiptDelivery(referenceNo,team,buyerCode,kind,sessionId);
for (int i=0; i<tmpList.size(); i++){
DeliveryPt dp = new DeliveryPt(tmpList.get(i));
rtnList.add(dp);
}
return rtnList;
}
}
DeliveryPt.java
public class DeliveryPt {
//2011.02.23 New Added DeliverySlipNo to show in flex
public String DeliverySlipSlipNo;
public DeliveryPt(Delivery delivery) {
this.setDeliveryNo(delivery.getDeliveryNo());
this.ReIncomeFlag = delivery.getReIncomeFlag();
ApplicationContext ac = CommonResource.getAppcontext();
StockMgr smgr = (StockMgr)ac.getBean("StockMgr");
Stock stock = smgr.getStock(delivery.getStock_Id());
if (delivery.getBooking() != null){
this.setOrderType(delivery.getOrderType());
this.setSalesOrderNo(delivery.getSalesOrderNo());
this.setRemark(delivery.getRemark());
this.setReferenceNo(stock.getReferenceNo());
// 유저 참조값 시작.
if(delivery.getDeliveryUser() != null){
this.setDeliveryUserName(delivery.getDeliveryUser().getName());
}
if(delivery.getInsertUser() != null){
this.setInsertUserName(delivery.getInsertUser().getName());
}
if(delivery.getUpdateUser() != null){
this.setUpdateUserName(delivery.getUpdateUser().getName());
}
if(delivery.getExpiredUser() != null){
this.setExpiredUserName(delivery.getExpiredUser().getName());
}
if (delivery.getBooking() != null){
if(delivery.getBooking().getInsertUser() != null){
this.setBookingUserName(delivery.getBooking().getInsertUser().getName());
}
}
// 유저 참조값 끝.
// 각종 날짜 입력.
if (delivery.getDeliveryDate() != null){
this.setDeliveryDate(delivery.getDeliveryDate());
}
if (delivery.getExpiredDate() != null){
this.setExpiredDate(delivery.getExpiredDate());
}
if (delivery.getInsertDate() != null){
this.setInsertDate(delivery.getInsertDate());
}
if (delivery.getUpdateDate() != null){
this.setUpdateDate(delivery.getUpdateDate());
}
if (stock.getSizeLabel() != null){
this.SizeLabelId = stock.getSizeLabel().getId();
}
this.Kind_id = stock.getKind_id();
this.StockId = delivery.getStock_Id();
// assigned value to varilable
this.DeliverySlipSlipNo = delivery.getDeliverySlip_SlipNo();
if (stock.getColorMst() != null){
this.ColorCode = stock.getColorMst().getColorCode();
this.ColorName = stock.getColorMst().getColorName();
}
this.Color_Name = stock.getColor_Name();
if (stock.getBuyer() != null){
this.BuyerCode = stock.getBuyer().getCode();
this.BuyerName = stock.getBuyer().getCode();
}
this.Team = stock.getTeam();
this.CancelFlag = delivery.getCancelFlag();
}
public String getBookingUserId() {
return BookingUserId;
}
public void setBookingUserId(String bookingUserId) {
BookingUserId = bookingUserId;
}
public String getDeliveryUserId() {
return DeliveryUserId;
}
public void setDeliveryUserId(String deliveryUserId) {
DeliveryUserId = deliveryUserId;
}
public String getInsertUserId() {
return InsertUserId;
}
public void setInsertUserId(String insertUserId) {
InsertUserId = insertUserId;
}
public String getUpdateUserId() {
return UpdateUserId;
}
public void setUpdateUserId(String updateUserId) {
UpdateUserId = updateUserId;
}
public Integer getSizeLabelId() {
return SizeLabelId;
}
public void setSizeLabelId(Integer sizeLabelId) {
SizeLabelId = sizeLabelId;
}
public Integer getKind_id() {
return Kind_id;
}
public void setKind_id(Integer kind_id) {
Kind_id = kind_id;
}
public Integer getStockId() {
return StockId;
}
public void setStockId(Integer stockId) {
StockId = stockId;
}
//Getter and Setter
public String getDeliverySlipSlipNo() {
return DeliverySlipSlipNo;
}
public void setDeliverySlipSlipNo(String deliverySlipSlipNo) {
DeliverySlipSlipNo = deliverySlipSlipNo;
}
}
Delivery.java
#Entity
#Table(name="Delivery")
public class Delivery {
public Delivery(){} // Default Constructor
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="DeliveryNo")
private Integer DeliveryNo;//2011.02.25 Added
#Column(name="DeliverySlip_SlipNo",length=20)
private String DeliverySlip_SlipNo;
//Getters an Setters for DeliverySlip_SlipNo
public String getDeliverySlip_SlipNo() {
return DeliverySlip_SlipNo;
}
public void setDeliverySlip_SlipNo(String deliverySlip_SlipNo) {
DeliverySlip_SlipNo = deliverySlip_SlipNo;
}
Have you added the new column to the equivalent action script object mapped to the Java object?