Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have one class release it contain list object of its self now i want that recursive list to get parsed and want it in one list.
Here is my class :
public class OnTimeNowRelease implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
int id;
String name;
String can_modify;
String start_date;
String due_date;
String velocity_start_date;
String release_notes;
String status;
String is_active;
String release_type;
List<OnTimeNowRelease> children ;
getter setter//
}
How can I traverse List of children up to nth level? its like traversing tree..if object does not have child its value is children = null
This is simple Traversal example, which you mostly see in LinkedList or Trees.
public void fetchAllChildren(OnTimeNowRelease root, List<OnTimeNowRelease> childList){
// if the parent is not defined, nothing to do
if(root == null){
return;
}
//add the parent to the list. Since java is Reference by Value, the list can be used for recursively adding all the descending elements
childList.add(root);
if(root.children !=null && !root.children.isEmpty()){
for(OnTimeNowRelease children : root.children){
//simple recursive solution add all the children and their children and so on....
fetchAllChildren(root.children, childList);
}
}
}
You could try something like:
public List<OnTimeNowRelease> flattenLists(OnTimeNowRelease obj) {
List<OnTimeNowRelease> result = new ArrayList<OnTimeNowRelease>();
List<OnTimeNowRelease> children = obj.getChildren();
if (children==null || children.isEmpty()) {
return result;
} else {
for (OnTimeNowRelease child : children) {
result.addAll(flattenLists(child));
}
}
return result;
}
This will iterate over all the children of each List and recursively add each of their child elements to one big list. You only have to initially call it with the root element once.
I don not know what yo want exactly: put in list all items in the tree to print it? move the childs of one item to his parent?
In the first case you can add a recoursive function to the class who obtain it:
public List<OnTimeNowRelease> obtainDescendants() {
// create a list for the childs
List<OnTimeNowRelease> items = new ArrayList<OnTimeNowRelease>();
// add myself
items.addAll(this);
if(children != null) {
// add my childs and his childs to the list
for(OnTimeNowRelease child : this.children) {
items.addAll( child.obtainDescendants() );
}
}
return items;
}
In the seconds case you can do something like
public void inherintChilds() {
if( children == null) {
return;
}
for(OnTimeNowRelease child : this.children) {
if( child.children != null) {
// take the childs
this.children.addAll(child.children);
// quit to my child
child.children = null;
}
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm working on a programming exercise, and I stumbled across a problem about "comparing" List objects for a method.
Goal: Check if the previous object in the List is null or if its next attributes points at my current object.
My idea was the following:
public ListElement (String info, ListElement next, ListElement prev) {
this.info = info;
this.next = next;
this.prev = prev;
}
public boolean isDeleted() {
ListElement prevElement = getPrev();
ListElement nextElement = getNext();
if(prevElement.next.info.equals(this.info))
return false;
}
However, I'm not sure if I get the correct result / about the approach.
Is there a better way to do this?
Assuming "points to" means "is the exact same instance", you'd have to use == for comparison.
public boolean isDeleted() {
return
// if the previous Object in the List is null
prev == null ||
// if its next attributes points at my current Object
next == this;
}
I have an object class which is contains a list of itself... Something like this:
public class SearchItemType implements Serializable {
protected List<SearchItemType> childItem;
}
The childItem also can conatain list of child items. My question is, can I iterate over childItems in all levels?
Right now my code looks like this:
public SearchItemType getElementByOpenedRowID(SearchItemType gridResult, String selectedRowId, Boolean found) {
SearchItemType element = new SearchItemType();
if (gridResult.getId().equals(selectedRowId)) {
element = gridResult;
found = true;
}
for (SearchItemType child : gridResult.getChildItem()) {
if (child.getId().equals(selectedRowId)) {
element = child;
found = true;
break;
}
}
if (!found) {
for (SearchItemType child : gridResult.getChildItem()) {
element = getElementByOpenedRowID(child, selectedRowId, found);
checkChildID(child, selectedRowId);
if (element != null) break;
}
}
return element;
}
Many thanks.
There is one error: at the start of the method, you set SearchItemType element = new SearchItemType(); but then check for null when you recurse. element will never be null. You can fix this by setting it to null at the start, but I have some suggestions about your code:
Instead of assigning the found value to an element and setting a found flag, just return the object as soon as you find it. At the end of the method return null. This will be much clearer.
Iterating over the children and checking them will currently be executed even if the parent was the one that was searched for. In fact, you can remove this loop entirely, as it is handled by the recursive step below.
Why are you passing found as a parameter? If you pass it true, then there is no point in having it, so if you really need it, just instantiate it in the method.
Make sure to check that gridResult is not null. You could remedy this by making getElementByOpenedRowID a method on SearchItemType, meaning that gridResult does not need to be passed.
Applying these changes will result in:
public SearchItemType getElementByOpenedRowID(SearchItemType gridResult, String selectedRowId) {
// stop at null
if (gridResult == null) {
return null;
}
if (gridResult.getId().equals(selectedRowId)) {
return gridResult; // return once found
}
// check all of the children
for (SearchItemType child : gridResult.getChildItem()) {
// do the search again for every child
SearchItemType result = getElementByOpenedRowID(child, selectedRowId);
if (result != null) {
// return once found and sent it all the way to the top
return result;
}
}
return null;
}
You can do this with recursion:
public void iterate(SearchItemType type) {
// Do something with type
for (SearchItemType child in type.childItem) {
iterate(child);
}
}
Yes you can iterate on childItem object at any level as long as childItem is not null and object inside it has non-null values.
In Data structure implementation of LinkedList every node in the LinkedList has Data fields link to other nodes (In case of Java it's reference to other nodes).
It's also called as self referencing objects that means object pointing to object of similar type.
As long as you have non-null values in the list you can iterate at any level.
Data structures in Java are implemented in similar manner.
Have look at Node class in this code snippet:
Linked List implementation using self referencing pointers
You want to iterate through the children recursively as so:
public SearchItemType getElementByOpenedRowID(SearchItemType gridResult, String selectedRowId) {
SearchItemType element = null;
if (gridResult == null) return null;
else if (gridResult.getId().equals(selectedRowId)) return gridResult;
else {
for (SearchItemType child : gridResult.getChildItem()) {
element = getElementByOpenedRowID(child, selectedRowId);
if (element != null) break;
}
}
return element;
}
I am writing a recursive method which traverse a hierarchy of Java objects. For this purpose I wrote a recursive method which takes the root node(parent) as parameter. Here is the base method which calls recursive method traverse:
if (category.id == GALLERIE_ID_TEST) {
traverse(category);
System.out.println("children ...." + subCategories);
}
And in the traverse method I wrote a logic which traverses all the child nodes of my parent node. But when I add all the child objects to a ArrayList, all children are not getting added to the final list from this method. Its returning only the child count of parent node but I need to get all the child nodes of the subsequent nodes too.
Here my code goes:
private static void traverse(KalturaCategory category)
throws KalturaApiException {
List<KalturaCategory> subCategories = new ArrayList<KalturaCategory>();
KalturaCategoryListResponse categoriesList = null;
if (category != null && category.directSubCategoriesCount >= 1) {
KalturaCategoryFilter filter = new KalturaCategoryFilter();
filter.parentIdEqual = category.id;
categoriesList = getCategoriesList(filter);
if (categoriesList.totalCount != 0) {
for (KalturaCategory subCat : categoriesList.objects) {
traverse(subCat);
subCategories.add(subCat);
}
}
System.out.println("subCategories Size ------>"
+ subCategories.size());
}
}
My output is:
subCategories Size ------>3
subCategories Size ------>4
subCategories Size ------>5
subCategories Size ------>5
subCategories Size ------>1
subCategories Size ------>6
children ....[]
But I want to get all this separate child objects into one ArrayList and return to my first method. Please help me resolving this. Thanks in advance.
The reason is you recursion is getting a copy of your array and return nothing to the original parent array [pass by value].
Try moving your category list outside the function and make it a global/static variable.
You might pass the single (!) List to receive all objects as a parameter in the recursive method:
private static void traverse(KalturaCategory category,
List<KalturaCategory> subCategories )
throws KalturaApiException {
if (category != null && category.directSubCategoriesCount >= 1) {
KalturaCategoryFilter filter = new KalturaCategoryFilter();
filter.parentIdEqual = category.id;
KalturaCategoryListResponse categoriesList =
getCategoriesList(filter);
if( categoriesList.totalCount != 0) {
for (KalturaCategory subCat : categoriesList.objects) {
traverse(subCat, subCategories);
}
subCategories.addAll( categoriesList.objects );
}
}
}
Change the first call accordingly, with the root node:
List<KalturaCategory> subCategories = new ArrayList<KalturaCategory>();
traverse( category, subCategories );
and subCateogories contains all objects from all nodes in the hierarchy.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In this method I'm suppose to remove all zeroes from a linkedlist but I'm not sure how to access the linked list. I am not allowed to change the parameters of the method but I can change the return. How can I access the linkedlist to modify it?
public domino removeZero() {
// ****** student exercise
return this;
}
This is the line that calls the method:
train = train.removeZero();
The name of the class is domino.
Here is the complete program http://pastebin.com/EwNJj9mV
You can use some getter setter method
like store your linkedlist in one different class's static variable and than in your method get that static variable's value.
import java.util.LinkedList;
public class linkedListStorage {
private static LinkedList linkedList;
public static LinkedList getLinkedList() {
return linkedList;
}
public static void setLinkedList(LinkedList linkedList) {
linkedListStorage.linkedList = linkedList;
}
}
now when you get your linkedlist put it via setter method
import java.util.LinkedList;
class JunitTest {
public static void main(String[] args) {
// set linked list to storage class's variable
linkedListStorage.setLinkedList(your linked list variable);
}
}
now use your linked list in your method
public domino removeZero() {
// ****** student exercise
// get your linked list from storage class
LinkedList ll = linkedListStorage.getLinkedList();
return this;
}
I suspect you need to learn some basics about object oriented programming and then re-ask the question. The method you have included in your question (removeZero) is a member of a class (domino) that has fields you can access inside the method. In other words removeZero has access to the linked list because it's a method of the linked list object.
In this case the code would be something like:
public domino removeZero() {
domino first = null;
for (domino current = this; current.next != null; current = current.next) {
if (current.spot1 == 0 || current.spot2 == 0) {
if (current.back != null)
current.back.next = current.next;
if (current.next != null)
current.next.back= current.back;
} else if (first == null) {
first = current;
}
}
return first;
}
By the way, you should tell your teacher to use capital letters to start class names. It should be called Domino, not domino.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
public class BinarySearchTree
{
public class TreeNode
{
private int item;
private TreeNode leftLink;
private TreeNode rightLink;
// One constructor for TreeNode
///////////////////////////////////////////////////////
public TreeNode(int newItem, TreeNode left, TreeNode right)
{
item = newItem;
leftLink = left;
rightLink = right;
}
} // End of TreeNode inner class
// Declaration of class BinarySearchTree begins here.
// Three instance variables.
private TreeNode root;
private TreeNode parent; // parent node of a target node being sought
private int parentLink; // pointer number of a parent node being sought
public BinarySearchTree( )
{
root = parent = null;
parentLink = 0; // no such pointer at the beginning
}
i want a deep copy for this tree, heading should be same as given below,
and it should work as describe,
This constructor will create a binary search tree which is a deep copy of an existing one that is given by the lone parameter of this constructor.
public BinarySearchTree (BinarySearchTree bst)
{
//your code should be here
}
// more codes here but given code is ok for question
}
You could add a function to your TreeNode:
public TreeNode deepCopy() {
return new TreeNode(item, leftLink.deepCopy(), rightLink.deepCopy())
}
Then:
public BinarySearchTree (BinarySearchTree bst) {
root = bst.root.deepCopy();
parent = bst.parent.deepCopy();
parentLink = bst.parentLink;
}
This is an example of course, you should pay attention to null value.
You can find a better example here: How to deep copy a tree?