Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Stack of Plates: Imagine a (literal) stack of plates. If the stack gets too high, it might topple.
Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of several stacks and should create a new stack once the previous one exceeds capacity.
SetOfStacks. push () and SetOfStacks. pop() should behave identically to a single stack (that is, pop ( ) should return the same values as it would if there were just a single stack).
I've implemented a solution with a HashMap.
I'd like to know if this is a good implementation (in space and complexity) and if it can be improve. Moreover, I've used correctly this.index ?
public class SetOfStacks {
private final int LIMIT= 5;
private HashMap<Integer,Stack<Integer>> setOfStack;
private int index;
public SetOfStacks(){
this.setOfStack= new HashMap<>();
this.index = 0;
}
public void addStack(){
this.index++;
if(!setOfStack.containsKey(index))
this.setOfStack.put(index, new Stack<Integer>());
}
public void pushElement(int value){
if (isFull())
addStack();
setOfStack.get(index).push(value);
}
public boolean isFull(){
return setOfStack.get(index).size() == LIMIT;
}
public void popElement(){
if(setOfStack.get(index).isEmpty())
index--;
setOfStack.get(index).pop();
}
public int peekElement(){
return setOfStack.get(index).peek();
}
}
FOLLOW UP
Implement a function popAt (int index) which performs a pop operation on a specific substack.
I didn't write the solution for it, but i think that his implementation should be easy. I only need to pass the parameter and just manage the push/pop, in case i need to refull that stack or not.
What do you think about maintenance of my code if you need to implement the follow up?
It's good but you have some mistake,
you never initialize the first stack,
also what happens if I initialize the SetOfStacks and call the pop?(assuming you fixed the first mistake)
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 have methode that returnd the smallest value in an arrayList. However, it should return anything if the arrayList is empty. Is there something I can do?
private int smallest() {
if(alList.empty()) {
//whatever will exit the
//function.
}
small = alList.get(0);
for(int i = 1, i <
alList.size(), i++) {
if(small > alList.get(i)){
small = alList.get(i)
}
}
return small;
}
//Thanks for your help.
Since you need to return an int, then no, you must return a value.
If you can change the method signature, you can:
Return an Integer and so return null.
Return Optional<Integer> and return an empty Optional.
There are many options. The three most obvious ones:
throw an exception: `if (alList.isEmpty()) throw new IllegalStateException("alList must not be empty when invoking smallest()");
decide on a sentinel value, for example 0, and return that. Update the docs to make it clear that 0 is returned for empty lists.
private int smallest(int valueIfEmpty) { if (alList.isEmpty()) return valueIfEmpty; ... } - i.e. pass the value to be returned in that case, so that the caller can decide what should happen.
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 3 years ago.
Improve this question
From immutability's point of view, is there any concerns for this code ?
public class mainPkg {
private boolean MyFunc1(MyInfo info) {
List<MyObj> myList = new ArrayList<MyObj>();
anotherPkg.MyFunc2(info, myList);
anotherPkg.MyFunc3(info, myList);
return CollectionUtils.isEmpty(myList);
}
}
public class anotherPkg {
public static boolean MyFunc2(MyInfo info, List<MyObj> myList) {
if(info.version < 2) {
myList.add(new MyObj('wrong version'));
return false;
}
return true;
}
}
MyFunc1(), MyFunc2() are used only in 1 place, and will only be used in this place. When i pass list as argument into myFunc2, it's like the classic call by reference. Not using global variable for myFunc1().
From immutability's point of view, what're are the concerns for this code ?
You are mutating the list referenced by myList in MyFunc2, therefore, your code is not immutable, therefore, it doesn't make sense to look at concerns "from immutability's point of view".
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
There is a status variable in a Java application that can be set to one of many statutes, depending on many conditions. The status field is a String. When a condition is met, the status should be returned immediately, as follows:
e.g
String status = "";
if (condition1) {
return "STATUS_1";
} else if (condition2) {
return "STATUS_2";
} else if (condition3) {
return "STATUS_3";
} else if (condition4) {
return "STATUS_4";
}
...
else if (condition10) {
return "STATUS_10";
}
I've considered which pattern would be best to make this code more SOLID... e.g. if a new condition is required then this class would need to edited to add the new condition, which would break the open / closed SOLID principle
I've looked at the Strategy Pattern, in particular "Replace Conditional Logic with Strategy", however that seems more appropriate when you want to decide on just one calculation / operation to use... My scenario does not seem to fit the Strategy Pattern as my logic determines the status, rather than determining which individual operation to execute - I need to run all the conditions until one is true
I wondered if the following pattern could work...
Have an interface as follows
public interace StatusCondition {
boolean condition(Context context);
String getStatus();
}
With an implementation as follows:
public class StatusAStatusCondition implements StatusCondition {
boolean condition(Context context){
return context.getValue1() == 0 && context.getValue2().equals("A");
}
String getStatus(){
return "STATUS_A";
}
}
This would allow a list of StatusCondition classes to be executed in order and return the status of the first StatusCondition where the condition() method returns true. e.g:
public String getStatus(List<StatusCondition> statusConditions) {
for (StatusCondition statusCondition : statusConditions) {
if (statusCondition.condition()) {
return statusCondition.getStatus();
}
}
return "";
}
usage:
List<StatusCondition> statusConditions = new ArrayList<>();
statusConditions.add(statusAStatusCondition);
statusConditions.add(statusBStatusCondition);
statusConditions.add(statusCStatusCondition);
statusConditions.add(statusDStatusCondition);
statusConditions.add(statusEStatusCondition);
statusConditions.add(statusFStatusCondition);
...
String status = getStatus(statusConditions);
To me this solves the open closed principle issue and also ensures the implementations are single responsibility... My question is, how could this pattern i've suggested be improved, or is there a pattern better suited to my scenario?
First, you are absolutely correct that the original if/else ladder violates the Open/Closed Principle. Second, converting the status value to an interface is exactly the right step to take, to move away from stringly-typed programming. Third, your solution is essentially the Chain of Responsibility Pattern. It's an excellent solution to this problem. In summary, your instincts are spot on.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
import java.util.*;
public class ass {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[]c={"sid","is","cool"};
List<String>list1=new ArrayList<String>();
for(String w:c){
list1.add(w);
}
String[]q={"is"};
List<String>list2=new ArrayList<String>();
for(String t:q){
list2.add(t);
}
EditList(list1,list2);
for(int i=0;i<list1.size();i++){
System.out.printf("%s ", list1.get(i));
}
}
public static void EditList(Collection<String>l1, Collection<String>l2){
Iterator<String>it=l1.iterator();
while(it.hasNext()){
if(l2.contains(it.next()));
it.remove();
}
}
}
In this programme I have two lists. I wanted to remove the items that are common in the first and second list from the first list and print it. I don't want a workaround or any other code suggestions. Can someone please explain why my code is not working?
I am following New Boston's tutorials.
Here:
if(l2.contains(it.next()));
it.remove();
That semicolon after if is a real statement.
Thus it.remove() happens always; like if ... that if not there!
Thus the real answer: always always always use
if (){
stuff
}
... even for single statements! Same for loops!
try
public static void EditList(Collection<String>l1, Collection<String>l2){
Iterator<String>it=l1.iterator();
while(it.hasNext()){
String current=it.next();
if(l2.contains(current)){
i1.remove(current); // assuming u wish to remove from l1
}
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
In my main class I want to check if there was a change by using a boolean variable:
public class Main {
private boolean change = false;
public boolean getChange() {
return change;
}
public void setChange(boolean change) {
this.change = change;
}
private void method1() {
// some command
setChange(true);
method1();
}
If I want to get this boolean value in my second class, I always get returned "false", no matter if my method1 ran or not.
public class BoolTest {
Main m = new Main();
System.out.println(m.getChange()); // returns "false"
}
You must have two instances of Main. Use the same one. Example:
Main m = new Main();
System.out.println(m.getChange());
m.setChange(true);
System.out.println(m.getChange());
You probably want to share the same instance over multiple classes. Pass the instance to the other classes and use them as expected.