I have a class with the boolean field and I want field of only one object to be true at the same time.
I tried to set field of all objects with static method but i could not reach non-static field from static method.(i wasn't aware of logic behind static)
public class ToggleBox
{
private boolean selected;
public ToogleBox()
{
selected=false;
}
public setOnlyTrue()
{
setAllFalse();
selected=true;
}
private static setAllFalse()
{
this.selected=false;
}
}
Is there any trick to do this or should i iterate over all objects of class to change all the fields?
One trick I could think of is having a static member that holds the reference of the one instance that has a true property:
public class MyClass {
private static MyClass trueObject = null;
public void setProperty(boolean value) {
if (value) {
trueObject = this;
} else {
trueObject = null;
}
}
public boolean getProperty() {
return trueObject == this;
}
}
It depends on you requirement when you want to create an instance with trueand a true has already been created
A. set ALL the others to false and the new one to true
public class ToggleBox {
private static List<ToggleBox> listAll = new ArrayList<>();
private boolean selected;
public ToggleBox(boolean bool) {
if (bool) // if require true
for (ToggleBox mo : listAll)
mo.setSelected(false); // set all other to false
listAll.add(this);
this.selected = bool;
}
public void setSelected(boolean bool) { this.selected = bool; }
#Override
public String toString() { return selected + ""; }
public static void main(String argv[]) {
ToggleBox m1 = new ToggleBox(true);
ToggleBox m2 = new ToggleBox(false);
System.out.println(Arrays.toString(listAll.toArray())); // [true, false]
ToggleBox m3 = new ToggleBox(true);
System.out.println(Arrays.toString(listAll.toArray())); // [false, false,true]
}
}
B. refuse to set the new one to true
public class ToggleBox {
private static boolean alreadyTrue = false;
private static List<ToggleBox> listAll = new ArrayList<>();
private boolean selected;
public ToggleBox(boolean bool) {
if (bool) { // if require true
if (alreadyTrue) // if there is already one
bool = false; // it will be false
else // else
alreadyTrue = true; // it's st to true, and remember it
}
this.selected = bool;
}
#Override
public String toString() { return selected + ""; }
public static void main(String argv[]) {
ToggleBox m1 = new ToggleBox(true);
ToggleBox m2 = new ToggleBox(false);
System.out.println(Arrays.toString(listAll.toArray())); // [true, false]
ToggleBox m3 = new ToggleBox(true);
System.out.println(Arrays.toString(listAll.toArray())); // [true, false, false]
}
}
Related
my code:
public class Kuh {
private String name;
private boolean istSatt;
public Kuh(String name, boolean istSatt) {
}
public double gibMilch() {
if (istSatt == true) {
System.out.println(10.0);
return 10.0;
} else {
System.out.println(3.0);
return 3.0;
}
}
public void grasen() {
istSatt = true;
}
public static void main(String[] args) {
Kuh Frida = new Kuh("Frida", true);
Frida.gibMilch();
Frida.grasen();
Frida.gibMilch();
}
}
My problem: I set "istSatt" of the object "Frida" to "true" at creation. So when using the method "gibMilch", it should put out "10". Despite that, it puts out "3", like the boolean would be false, even tho I set it to true. It only puts out "10" after using "grasen".
What did I do wrong?
You are not assigning the constructor parameters to the fields.
public Kuh(String name, boolean istSatt) {
this.name = name;
this.istSatt = istSatt;
}
You need to set your class variable values in your constructor:
public Kuh(String name, boolean istSatt) {
this.name = name;
this.istSatt = istSatt;
}
Here this refers to the class you are instantiating.
Try this instead, as you did not seem to assign to anything on the call to Kuh Frida = new Kuh("Frida", true);
i.e.
public class Kuh {
private String name;
private boolean istSatt;
public Kuh(String name, boolean istSatt) {
this.istSatt=istSatt;
this.name=name;
}
public double gibMilch() {
if (istSatt) {
System.out.println(10.0);
return 10.0;
} else {
System.out.println(3.0);
return 3.0;
}
}
public void grasen() {
istSatt = true;
}
public static void main(String[] args) {
Kuh Frida = new Kuh("Frida", true);
Frida.gibMilch();
Frida.grasen();
Frida.gibMilch();
}
}
I am trying to understand the Memento Pattern. For that purpose i am trying to implement the undo function. The problem is that when ever i save the old state of the originator in the queue and run a different function the save state changes to the current state. I really need help to understand what i am doing wrong. How can i make the vector to be immutable.
This is the memento class.
package memento;
public class Memento
{
private final boolean[] vectorState;
public Memento(boolean[] vector) {vectorState = vector;}
boolean[] getMemento() { return vectorState;}
}
The Originator just need to shift a vector of boolean to the left.
(TRUE,FALSE,FALSE) shift left returns: (FALSE,FALSE,TRUE). This is the implementation.
package memento;
public class ShilftLeftOriginator
{
private boolean[] vector;
public ShilftLeftOriginator(boolean[] vector) {this.vector = vector;}
public void execute()
{
final boolean firstValue = this.vector[0];
for (int i = 1; i < this.vector.length; i++) {
this.vector[i - 1] = this.vector[i];
}
this.vector[vector.length - 1] = firstValue;
}
public Memento saveToMemento() {return new Memento(vector);}
}
And the caretaker:
package memento;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
public final class BooleanVector {
private boolean[] vector;
private Deque<Memento> mementoList = new LinkedList<>();
public BooleanVector(boolean[] inputValues) {
this.vector = inputValues;
}
#Override
public boolean equals(Object obj)
{
if (obj == null) return false;
if (!(obj instanceof BooleanVector)) return false;
BooleanVector otherVector = (BooleanVector) obj;
return Arrays.equals(this.vector, otherVector.vector);
}
public void shiftLeft()
{
ShilftLeftOriginator shiftLeft = new ShilftLeftOriginator(vector);
mementoList.add(shiftLeft.saveToMemento());
shiftLeft.execute(); // This is my Problem. After execute ist call the value(vector) in mementoList changes
}
public void undo(){ this.vector = mementoList.pop().getMemento();}
}
And now the test class and the error that i am receiving.
package memento;
public class Main {
public static void main(String[] args) {
boolean[] inputValues = { false, true, false };
BooleanVector vector = new BooleanVector(inputValues);
vector.shiftLeft();
boolean[] expectedValues = new boolean[] { true, false, false };
BooleanVector expectedVector = new BooleanVector(expectedValues);
if (!vector.equals(expectedVector)) {
throw new IllegalStateException(vector.toString());
} else {
System.out.println("shiftleft working");
}
vector.undo();
expectedValues = new boolean[] { false, true, false };
expectedVector = new BooleanVector(expectedValues);
if (!vector.equals(expectedVector)) {
throw new IllegalStateException(vector.toString());
} else {
System.out.println("undo working");
}
}
}
The console output:
shiftleft working
Exception in thread "main" java.lang.IllegalStateException: [true, false, false]
at memento.Main.main(Main.java:26)
The problem is that you're always manipulating the same array. So if you shift left, you also shift left the array you stored in the Memento object, because it's all the same array.
To solve it, make a copy of the array in the constructor of the Memento object:
public Memento(boolean[] vector) {
vectorState = Arrays.copyOf(vector, vector.length);
}
Aside from that, you seem to have your classes mixed up. BooleanVector and ShilftLeftOriginator are the originator, while Main is the caretaker.
I can give you a little bit more expandable solution:
class Originator: abstract implementatino of the value T holder
public abstract class Originator<T> {
private T value;
private final CareTaker<T> careTaker;
protected Originator(T value, CareTaker<T> careTaker) {
this.value = value;
this.careTaker = careTaker;
}
public final T getValue() {
return value;
}
protected final void setValue(T value) {
careTaker.add(this.value);
this.value = value;
}
public final void undo() {
if (!careTaker.isEmpty())
value = careTaker.remove();
}
}
class BooleanVector: concrete implementation that holds boolean[]
public final class BooleanVector extends Originator<boolean[]> {
public BooleanVector(boolean[] obj) {
super(obj, new CareTaker<>());
}
public void leftShift() {
if (getValue() == null || getValue().length == 0)
return;
boolean[] arr = new boolean[getValue().length];
boolean tmp = arr[0];
System.arraycopy(getValue(), 1, arr, 0, getValue().length - 1);
arr[arr.length - 1] = tmp;
setValue(arr);
}
}
class CareTaker: implementation of values change history - memento
public final class CareTaker<T> {
private final Deque<Item<T>> stack = new LinkedList<>();
public void add(T value) {
stack.push(new Item<>(value));
}
public T remove() {
return stack.pop().data;
}
public boolean isEmpty() {
return stack.isEmpty();
}
private static final class Item<T> {
private final T data;
public Item(T data) {
this.data = data;
}
}
}
Demo:
public static void main(String[] args) {
BooleanVector originator = new BooleanVector(new boolean[] { false, true, false });
System.out.println(Arrays.toString(originator.getValue()));
System.out.println("---");
originator.leftShift();
System.out.println(Arrays.toString(originator.getValue()));
originator.undo();
System.out.println(Arrays.toString(originator.getValue()));
}
Output:
[false, true, false]
---
[true, false, false]
[false, true, false]
In all the searching I did, I could not find an example of this sort. My bad :(
I have an Optional object containing an array. I now need to traverse the array and locate a particular element inside it.
Codes and sample classes as follows:
public class Component {
private String name;
public Component(String ipName) {
this.name = ipName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Container {
private Component[] componentArray;
public Container(Component[] ipComponentArray) {
this.componentArray = ipComponentArray;
}
public Component[] getComponentArray() {
return componentArray;
}
public void setComponentArray(Component[] componentArray) {
this.componentArray = componentArray;
}
}
public class TestClass {
public static void main(String[] args) {
Container newContainer = getNewContainer();
System.out.println(checkIfComponentIsPresent("Two", newContainer)); //prints true
System.out.println(checkIfComponentIsPresent("Five", newContainer)); //prints false
}
private static Container getNewContainer() {
return new Container(new Component[] {new Component("One"), new Component("Two"), new Component("Three")});
}
private static boolean checkIfComponentIsPresent(String ipName, Container newContainer) {
boolean isPresent = false;
Optional<Component[]> componentArrayOptional = Optional.ofNullable(newContainer).map(Container::getComponentArray);
if(componentArrayOptional.isPresent()) {
Component[] componentArray = componentArrayOptional.get();
if(componentArray != null && componentArray.length > 0) {
for(Component component : componentArray) {
if(ipName.equals(component.getName())) {
isPresent = true;
break;
}
}
}
}
return isPresent;
}
}
Can someone please advise me how can I improve the method checkIfComponentIsPresent? I want to know how can we traverse an array inside an Optional object, without converting it into a list or stream.
I can do it using streams as follows:
private static boolean checkIfComponentIsPresentUsingStreams(String ipName, Container newContainer) {
boolean isPresent = false;
Optional<Component[]> componentArrayOptional = Optional.ofNullable(newContainer).map(Container::getComponentArray);
if(componentArrayOptional.isPresent()) {
Stream<Component> componentArrayStream = Arrays.stream(componentArrayOptional.get());
isPresent = componentArrayStream.filter(component -> ipName.equals(component.getName())).findFirst().isPresent();
}
return isPresent;
}
But I cannot use streams, actually my classes are huge, and the array itself can contain numerous elements. Using streams, will degrade the performance.
Thanks!
You can operate with actual object value inside map method:
boolean isPresent = Optional.ofNullable(newContainer)
.map(Container::getComponentArray)
.map(arr -> {
for (Component component : arr) {
if (Objects.equals(component.getName(), ipName)) {
return true;
}
}
return false;
})
.orElse(false);
Actually I am sure what makes you think Stream would slow down your app significantly. And therefore there is another solution using streams:
boolean isPresent = Optional.ofNullable(newContainer)
.map(Container::getComponentArray)
.map(arr -> Stream.of(arr).anyMatch(component -> Objects.equals(ipName, component.getName())))
.orElse(false);
This is what I have:
public static void main(String[] args){
Main main = new Main();
boolean shouldBeTrue = main.shouldBeTrue();
shouldBeTrue = true;
System.out.println(shouldBeTrue);
System.out.println(main.shouldBeTrue());
}//close main
public boolean shouldBeTrue(){
return false;
}
It prints: true false
However I would to assing main.shouldBeTrue() = true;
which does not work.
My goal is to print main.shouldBeTrue() and have it print true instead of false.
Any ideas?
Thank you all so so much!
System.out.println(main.shouldBeTrue());
The above is line is actually calling shouldBeTrue(), which is returning false.
Either pass a boolean variable to a method and return that values.
public boolean shouldBeTrue(boolean myValue) {
return myValue;
}
For main.shouldBeTrue() to return true, the reference it returns should point to a value of true.
public class Main {
private boolean whatDoIReturn = false;
public static void main(String[] args){
Main main = new Main();
Boolean shouldBeTrue = main.shouldBeTrue();
main.shouldBeTrue( shouldBeTrue = true);
System.out.println(shouldBeTrue);
System.out.println(main.shouldBeTrue());
}//close main
public Boolean shouldBeTrue(){
return whatDoIReturn;
}
public void shouldBeTrue(boolean value){
this.whatDoIReturn = value;
}
}
As others have already mentioned, you can not assign a value to a method! What you need to do is maintain a variable that the method will return.
class MyClass
{
private boolean myReturnValue = false; // can be set to either true or false
public boolean shouldBeTrue()
{
return myReturnValue;
}
// Use this method to set the return value.
public void setMyReturnValue( boolean newValue )
{
myReturnValue = newValue;
}
public static void main( String[] args )
{
MyClass myClass = new MyClass();
System.out.println(myClass.shouldBeTrue()); // this will return false, which is currently the defined value of myReturnValue
// Now we will change the return value.
myClass.setMyReturnValue(true);
System.out.println(myClass.shouldBeTrue()); // Now it will return true.
}
}
I have this simple Bean class and try to set some values with BeanUtils.setProperty Problem is, it seems that String works just fine, but when I try to set a Boolean value it just does not work. I have tried and define the field as public but still not working. Any help? Why is this not working?
public class TestBean {
protected Boolean someBoolean;
protected String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSomeBoolean() {
if (someBoolean == null) {
return true;
} else {
return someBoolean;
}
}
public void setSomeBoolean(Boolean value) {
this.someBoolean = value;
}
public static void main(String[] args) {
TestBean o = new TestBean();
Boolean b = new Boolean(false);
BeanUtils.setProperty(o, "someBoolean", b);
BeanUtils.setProperty(o, "name", "A name");
System.out.println(((TestBean)o).isSomeBoolean());
// Output = true WHY?????
System.out.println(((TestBean)o).getName());
// Output = A name
BeanUtils.setProperty(o, "someBoolean", false);
BeanUtils.setProperty(o, "name", "Another name");
System.out.println(((TestBean)o).isSomeBoolean());
// Output = true WHY????
System.out.println(((TestBean)o).getName());
// Output = Another name
}
}
You need to change it from
protected Boolean someBoolean;
to
protected boolean someBoolean;
You will get more info from here.
Java Beans, BeanUtils, and the Boolean wrapper class