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.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm currently facing this problem in Java, lets say I have a class ListOfTasks:
public class ListOfTasks {
private Point startingPoint;
ArrayList<Task> tasks;
}
In another class, I want to iterate through the array list tasks directly by calling ListOfTasks, and not by retrieving tasks first and then iterate through it.
You can do this by implementing Iterable to return the iterator of the array list:
public class ListOfTasks implements Iterable<Task> {
private Point startingPoint;
ArrayList<Task> tasks;
public Iterator<Task> iterator() {
return tasks != null ? tasks.iterator() : Collections.emptyIterator();
}
}
You can then iterate using a for-each
ListOfTasks list = new ListOfTasks();
// add some tasks, etc...
for (Task task : list) {
// use task
}
// or
list.forEach(task -> {
// use task
});
there are many ways to do that:--
Write GETTER/SETTER inside ListOfTasks POJO.
public class ListOfTasks {
private Point startingPoint;
ArrayList<Task> tasks = new ArrayList<>();
GETTER/SETTER
}
then
ListOfTasks list = new ListOfTasks();
for(int i=0 ;i<list.getTask().size();i++){
list.getTasks().get(i);
}
Something like this should work, if I understand your question:
for (int i = 0; i < listOfTasksObject.tasks.size(); i++) {
Task task = listOfTasksObjects.tasks.get(i);
// Now you can work with task...
}
The approach you are taking is wrong, because the responsibility of the property "tasks" is owned by the class ListOfTasks.
So you have to change the approach, and iterate through the set of ListOfTasks instances you have in the other class and call a method, let's say
public Task findTask() {
// do something here to find the Task you were looking for, or return null
}
so the other class should look like this:
List<ListOfTasks> lists = new ArrayList<>();
// populate list here ...
Task found = lists.stream().filter(x => x.findTask()).filter(x => x != null).findAny().orElse(null);
Just dont expose getter for tasks.
create a method in ListOfTasks class like :
public Task get(int index){
return list.get(index);
}
public int size(){
return list.size();
}
now use ListOfTasks like this
for(int i=0 ;i<listOfTasks.size();i++){
// now access Task like this
listOfTasks.get(i);
}
I have been trying to create (I have been learning it) a doubly linked list based on an exercise, in which the list will be train with wagons. The exercise asks to create a class "wagon" with the attributes "name of wagon", "next wagon" and "previous wagon", and another class "train" with the methods to add wagons, print the wagons and sawp the order of the locomotives of the trains. My problem is in how the exercise asks to create the method to add wagons, and the one to swap the order of the locomotives. The method to add wagons has a parameter that has as data type the class "wagon", and I have really not gotten to create this method. I am going to show you what I have already done in the code below. Could anyone help me with that? I have not understood how to use the parameter "vagaoCriar" in the method.
Besides that, the exercise asks to create two trains (then two lists), and to change the two locomotives of the two trains. I would like to know if that is really possible with two doubly linked lists, to swap two elements of them between themselves, or could it be simply swapping the order of the two doubly linked lists, without having to change elements between them? Because I have already searched it enough and I have not found anything saying that it is possible to swap elements between two doubly linked lists. Still, I have had some problem to create the method to swap the locomotives of the train, because the method has as data type "wagon", but it has as parameter "name of wagon" (String), and the name of the method is "get wagon and remove", so I do not have idea what the exercise really wishes.
I understand that the questions is long, but for such a complex example (for me), I could not be concise.
public class Vagao {
String nomeDoVagao;
Wagon vagaoAnterior;
Wagon vagaoPosterior;
public Vagao (String nomeDoVagao){
this.nomeDoVagao = nomeDoVagao;
vagaoAnterior = null;
vagaoPosterior = null;
}
}
public class Trem {
Vagao head, tail = null;
//I do not know to proceed here
public void adicionarVagao (Vagao vagaoCriar){
Vagao novo_Vagao = new Vagao (vagaoCriar.nomeDoVagão);
if (head == null){
head = tail = novo_Vagao;
head.vagaoAnterior = null;
tail.vagaoPosterior = null;
} else {
tail.vagaoPosterior = novo_Vagao;
novo_Vagao.vagaoAnterior = tail;
tail = novo_Vagao;
tail.vagaoPosterior = null;
}
}
//This is the other method, that I have not understood well, so I have not
even begun it
public Vagao pegarVagaoRemover (String nomeDoVagao){...}
}
This is how I have tried to create a "train" and print it in the console, but it has not worked:
public class Main {
public static void main(String[] args) {
Trem trem = new Trem();
trem.adicionarVagao("qualquer");
trem.printTrem();
}
}
head and tail are not indepedant wagons themselves.
So one should not alter head's or tail's fields in general.
Adding at the end:
novo_Vagao.vagaoAnterior = null;
novo_Vagao.vagaoPosterior = null;
if (head == null){
head = tail = novo_Vagao;
} else {
novo_Vagao.vagaoAnterior = tail;
tail.vagaoPosterior = novo_Vago;
tail = novo_Vagao;
}
Removal would go:
if (vagao.vagaoPosterio == null) {
tail = vagao.vagaoAnterior;
} else {
vagao.vagaoPosterio.vagaoAnterio = vagao.vagaoAnterior;
}
...
So: what referencing fields to change.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to update a enqueue function of a queue class so that it enqueue a stack item (nrm LIFO stack) according to its size.
But when I try to use the variable for the size of the stack (N) it says variable can't be resolved or it is not a field. All fields and methods are public in all classes.
public void add(SpecialStack SpecialStack) {
Node<SpecialStack> oldlast = last;
last = new Node<SpecialStack>();
last.astack = SpecialStack;
int a = last.astack.N;
last.next = null;
if (isEmpty())
first = last;
else
oldlast.next = last;
N++;
}
This is the function who is problematic, and the class which i want to add:
public class SpecialStack {
public Node <Integer> first;
public int N;
public static class Node <Integer> {
public Integer value;
public Node next;
Node (Integer a) {
value = a;
}
}
}
N exists inside SpecialStack, not inside WhateverClassDeclaresTheAddMethod, yet you try to do N++ inside WhateverClassDeclaresTheAddMethod. To fix the compile problem you would need to do last.astack.N++ instead, but that doesn't make sense because that's the size of the SpecialStack, not the size of the Queue.
You really need an N inside of Queue so you can increment that.
(Note: please don't name your variables and fields using something that starts with an upper case letter. That makes most of us cringe.)
As for the problem on int a= last.astack.N... you haven't declared last.astack to be of type SpecialStack. You've made it something else, something more general, that doesn't have an N. So even though the object stored in last.astack is a SpecialStack and has an N, the compiler can't tell because it can't see the instance at compile time.
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;
}
}
}
I'm a Java novice trying to get a set of activities, with start and end times, into a linked list and then optimize the schedule for the room these activities will take place in. I have the linked list created and it seems I have succeeded to pass it into my maxRoomUse method where I will do the schedule. I am having trouble understanding how to iterate through my list in the maxRoomUse method. I am not allowed to import any packages to help me.
You can define a nested iterator class inside List class.
ListIterator implements Iterator, and which has 3 methods.
The implementation is like this.
public boolean next() {
return current == null;
}
public Activity next(){
if (! this.hasNext())
throw new IllegalStateException();
//if (this.curModCount != modCount)
// throw new ConcurrentModificationException()
Activity data = this.current.activity;
this.current = this.current.next();
return data;
}
public void remove(){
throw new UnsupportedOperationException();
}