I have two stacks.
I want to be able to push any element onto one, but only if it was popped off the other.
Instead of My current function looks like this:
public void pushValue(int poppedValue) {
Stack.push(value)
}
I want the function to look something like this:
public void pushValue(pop() poppedValue) {
Stack.push(value)
}
How could I set the pop() function as a parameter, instead of an int?
In other words, how can I set the parameter to only accept a value that was popped from somewhere?
There is no way in Java to express that constraint. (Or in any other language, AFAIK)
(IMO) the best you can do is to pass the second Stack as an argument to the first one and make the first one responsible for popping a value; e.g.
public class Stack {
...
public int transferValue(Stack source) {
int res = source.pop(); // throws exception if source is empty
this.push(value);
return res;
}
}
This leaves you with problems regarding push:
Do you remove it entirely from the Stack API? If so, how do the elements get onto the source stack?
Do you split the Stack API into Stack and StackWithoutPush? If yes, which is the super-class / super-interface? Neither alternative is perfect. Either way, the subclass violates the contract of the superclass in some sense. (C.f. the problem of List versus UnmodifiableList APIs.)
Your syntax isn't possible, but you could make the second stack a member field and then push iff the value is present when you peek at the second stack (through the field).
private Stack otherStack = null; // <-- set this somehow (constructor?), or pass it.
public void pushValue(int newValue) {
if (otherStack != null && otherStack.peek() == newValue) {
Stack.push(newValue); // <-- please observe naming conventions (stack)
}
}
Then, pop() the value. Basically, peek, push and then pop.
Related
I am trying to implement kind of Stack, which has push(), pop(), getMaxSoFar().
It should be executed o(1) time. However, I got an error in push(T value), and I don't know why. The error message said the operator ">=" is not defined in the type of T. I just wanted to check the code so I put int type instead of then it worked.
class FastMaxStack<T>
{
private Stack<T> stack;
private Stack<T> maxStack;
public FastMaxStack()
{
stack = new Stack();
maxStack = new Stack();
}
public void push(T value)
{
if(maxStack.isEmpty())
{
maxStack.push(value);
}
else if(value >= maxStack.peek())
{
maxStack.push(value);
}
stack.push(value);
}
public T pop()
{
maxStack.pop();
return stack.pop();
}
public T getMaxSoFar()
{
return maxStack.peek();
}
}
Your push method is assuming that the >= operator is supported for every conceivable type T. However, that operator is only supported for numeric types.
Perhaps you should define your class to operate for integers only, and not any data type.
On the other hand, perhaps you could implement your class for all Comparables.
class FastMaxStack<Comparable<T>>
{
//etc...
}
(too long for a comment)
There is another problem.
push always pushes on stack, but only pushes on maxStack if the value is at least as large as the top. So far, so good.
But pop always pops from both. Two problems:
Even if you pop as many times as you push, there can be an EmptyStackException if maxStack does not have enough elements (which will happen if you don't push values in increasing order).
Even if there is no exception, the value of getMaxSoFar won't be correct. As I understand what you are trying to do, maxStack is supposed to hold in top the max element of the stack in its current state. But imagine you push a value smaller than top, maxStack is not updated, and if you pop (from both then), the max is lost in maxStack. But it's still here in stack.
I have a snippet as below
private String getString() {
List<String> stringList = Arrays.asList("s1", "s2");
stringList.forEach(item ->
{
if (item.equals("s1"))
return item;
});
return null;
}
Now I get a compilation error Void methods cannot return a value while I try to return item. I googled and couldn't understand why this is happening and the solution to this problem. How do I return item in the above forEach loop?
forEach is a consumption process. The functions passed to a forEach method are expected to have side effects which do not directly result in a value being returned, like printing the contents of the list, or doing some side operation.
Basically, any function that is a Consumer or method that returns void is fair game here.
Since you're explicitly looking for a value, you can use Stream#findAny() instead.
// You don't do anything with the result you want anyway,
// so I'm simply printing it out. You should determine what you need to do
// with the value you get back.
Optional<String> findResult = stringList().stream().findAny(v -> v.equals("s1"));
findResult.ifPresent(System.out::println);
I think you've misunderstood lambdas. A lambda is an executable statement that may be executed immediately, or deferred; more importantly, it has its own method signature.
In the following code, you've defined an anonymous method. What is its signature?
stringList.forEach(item ->
{
if (item.equals("s1"))
return item;
});
The answer is that your anonymous method has the following equivalent representation:
private void myAnonymousMethod( String item ) {
if ( item.equals("s1"))
return item;
}
Do you now see your mistake? Your anonymous method has a void return type, but you're trying to return a value.
Instead, you could fix this in a variety of ways:
When you find the value you're looking for, save it in a local variable outside the scope of the lambda. Pro: introduces the smallest amount of change to your code. Con: the foreach loop will continue to execute after it finds its first match.
Use a different iterator method, such as findAny as indicated in Makoto's post.
Replace the anonymous method entirely with a normal loop.
I provide an API and need to know, where methods of the API were invoked. I could of cause use reflection or the thread stacktrace, but that would include a lot of runtime cost.
I do not need the exact class name, a unique reference per invocation would be sufficient. In C I would normally use the preprocessor to automatically add __FILE__ and __LINE__ to the method invocation.
Is there a method in Java (besides code generation) to get a unique caller identification with low runtime cost?
One solution would be to have a cached Throwable which is passed in.
class StackPoint {
Throwable stack;
public Throwable getStack() {
if (stack == null)
stack = new Throwable();
return stack;
}
}
public void methodToCall(StackPoint sp) {
Throwable t = sp.getStack();
}
static final StackPoint one = new StackPoint();
methodToCall(one); // Have to remember to give each line a different StackPoint.
Note: if the method which calls this caller changes, you only record the first one ever.
There isn't a standard pattern and it is likely that if you want this to be efficient the caller will need to pass a unique id. The closest you can do is use is a lambda.
public void methodToCall(Runnable run) {
Class id = run.getClass();
}
You can call it like this
methodtoCall(()->{});
This will create a different class for each place it is called, even if it appears multiple times on the same line. It creates no garbage as it reuses the same object each time. You could make this shorter with
void methodToCall(IntFunction fun) {
}
and call
methodToCall(a->1);
As something asynchroneous is involved, split the call up, and let the API return the ID.
Ticket callTicket = api.call(params);
Logger.getLogger(getClass().getName(), Level.FINE, callTicket);
Result result = callTicket.get();
Above having a result returned (synchroneously) is probably not the case with your code. Your code will get the result delived elsewhere. But that could be a ticket system too.
Consider:
class TestParent{
public int i = 100;
public void printName(){
System.err.println(this); //{TestChild#428} according to the Debugger.
System.err.println(this.i); //this.i is 100.
}
}
class TestChild extends TestParent{
public int i = 200;
}
public class ThisTest {
public static void main(String[] args) {
new TestChild().printName();
}
}
I know that similar questions have been asked, but I couldn't get a firm understanding of the 'this' variable in Java.
Let me try to explain how I understand the result of the above image.
Since it's a new TestChild() object that's calling the printName() method, the this variable in line 6 is set to a TestChild object - {TestChild#428} according to the Debugger.
However, since Java doesn't have a virtual field - I'm not completely sure what this means, but I conceptually understand it as being the opposite of Java methods, which support Polymorphism - this.i is set to 100 of TestParent at compile time.
So no matter what this is, this.i in a TestParent method will always be the i variable in the TestParent class.
I'm not sure that my understanding is correct so please correct me if I'm wrong.
And also, my main question is,
How is the this variable set to the current object that's calling the method? How is it actually implemented?
In essence, there is no difference between
this.foo()
and
anyObject.foo()
as both are "implemented" the same way. Keep in mind that "in the end" "object orientation is only an abstraction, and in "reality" what happens is something like:
foo(callingObject)
In other words: whenever you use some object reference to call a method ... in the end there isn't a call on some object. Because deep down in assembler and machine code, something like "a call on something" doesn't exist.
What really happens is a call to a function; and the first (implicit/invisible on the source code level) parameter is that object.
BTW: you can actually write that down in Java like:
class Bar {
void foo(Bar this) { ... }
and later use
new Bar().foo();
And for this.fieldA, in the end: you have a reference to some location in memory; and a table that tells you on which "offset" you will find fieldA.
Edit - just for the record. If you are interested in more details about foo(Bar this) - you can turn to this question; giving the details in the Java spec behind it!
What's happening here is that there are two completely different fields both called i; to use their full names, one is TestParent::i and one is TestChild::i.
Because the method printName is defined in TestParent, when it refers to i, it can only see TestParent::i, which is set to 100.
Whereas when you set i to 200 in TestChild, both fields called i are visible, but because they have the same name, TestChild::i hides TestParent::i, and you end up setting TestChild::i and leaving TestParent::i untouched.
Well when a new object is created that object has an address in memory so you can think of it as if the object had a private member this that is set to the address when the object is created. You can also think of it like this: obj.method(param) is just syntactic sugar for method(obj, param); and this is actually a parameter of method.
To directly address what you see in the output: The call to print 'this.i' is passing as argument to 'print()' the value of the field 'i' in the current scope, which is the scope of the parent class. By contrast, the call to print 'this' is getting translated under the hood to a call to print 'this.getClass().getName()' [roughly speaking], and the 'getClass()' call gets the actual class object, which is for the child class.
Adding some more info on top of #Tom Anderson answer, which explains hiding concept nicely.
I have added one more constructor in Child ( TestChild) which prints values of i in both parent and child.
If you want get value of i from child (TestChild), override the method in TestChild.
class TestParent{
public int i = 100;
public void printName(){
System.err.println("TestParent:printName()");
System.err.println(this); //{TestChild#SOME_NUM} according to the Debugger.
System.err.println(this.i); //this.i is 100.
}
}
class TestChild extends TestParent{
public int i = 200;
public TestChild(){
System.out.println("TestChild.i and TestParent.i:"+this.i+":"+super.i);
}
public void printName(){
//super.printName();
System.err.println("TestChild:printName()");
System.err.println(this); //{TestChild#SOME_NUM} according to the Debugger.
System.err.println(this.i); //this.i is 200.
}
}
public class ThisTest {
public static void main(String[] args) {
TestParent parent = new TestChild();
parent.printName();
}
}
Case 1: If I comment super.printName() call from child, Child version of TestChild.printName() prints the value of i in TestChild
Output:
TestChild.i and TestParent.i:200:100
TestChild:printName()
TestChild#43cda81e
200
Case 2: TestChild.printName() calls super.printName() as the first line in printName() method. In this case, i value from both parent and child are displayed in respective methods.
Output:
TestChild.i and TestParent.i:200:100
TestParent:printName()
TestChild#43cda81e
100
TestChild:printName()
TestChild#43cda81e
200
I am writing a program that generates a maze and then finds a path. I store all my moves into a stack called visitStack (if I move north, I store "N" into it, if Northeast then "NE", on and on). For part of my backtracking I need to be able to take the data from the stack and reverse my steps if I hit a dead end, but I've hit a snag here.
I need to assign a value popped from a stack to a String variable, but I always get a compiler error. I've tried using toString, instantiating the String as an object with the popped stack value as the parameter, and still can't get it. I've been on this for about an hour. Here is the code and error message.
String direction = visitStack.pop();
Assuming that you are using java.util.Stack I suspect that you didn't describe what type of elements it should store, which is why compiler sees return type of pop as Object (common ancestor of all types).
Also assuming that stack should store only String elements it should be declared as
Stack<String> visitStack = new Stack<String>();
Now compiler should see return type of pop() as String which will allow you to store its result in other String type reference
String direction = visitStack.pop();
Above solution is preferred when you are sure that stack can contain only strings, but if there are some other elements you will need to either explicitly cast returned object to String (if you are sure that it will be instance of String) like
String direction = (String) visitStack.pop();
or if you are not sure what object will be returned calling toString() method to get its string representation:
String direction = visitStack.pop().toString();
If you define your stack as Stack<String>, pop() will return a String, and you won't need to mess around with casting. If you cannot, for some reason, and you're positive the object being popped is a String, you can cast it explicitly:
String direction = (String)visitStack.pop();
Since you are using a limited number of possible values you shloud use ENUMS for type Safety.
Use :
Stack<Direction> visitStack=new Stack<>();
visitStack.push(Direction.EAST);
Direction dir=visitStack.peek();
String dir2=visitStack.pop().toString();
System.out.println(dir);
System.out.println(dir2);
your Direction should look like:
public enum Direction {
North("N"), NORTH_WEST("NW"), NORTH_EAST("NE"), EAST("E")
, SOUTH_EAST("SE"), SOUTH("S"), SOUTH_WEST("SW"), WEST("W");
private String shortName;
private Direction(String shortName) {
this.shortName = shortName;
}
#Override
public String toString() {
return this.shortName;
}
}