I want to know, in the code provided what does 'this' keyword referring to.? - linked-list

/*
I know this keyword is used to refer to class members but i am unable to understand what does 'this'.isEmpty() referring to. Some class ? class method? Or some variable?
For example:
this.value = value;
I understand that here, this.value is referring to class variable value but not for previous occurence of 'this'.
*/
public class StackWithMin extends Stack< NodeWithMin > {
public void push(int value) {
int newMin = Math.min(value, min());
super.push(new NodeWithMin(value,newMin));
}
public int min() {
if(this.isEmpty()) {
return Integer.MAX_VALUE; // Error value
} else {
return peek().min;
}
}
}
class NodeWithMin {
public int value;
public int min;
public NodeWithMin(int value, int min) {
this.value = v;
this.min = min;
}
}

"this" here is object of the class StackWithMin which is extending Stack class from java.util. so StackWithMin is instance of Stack class.
this.isEmpty() which is method defined in Stack, here checks if the stack has any element or not. if it has zero element it returns true else false.
Hope it clears your doubt.

Related

Dart can't access property on a generic type function parameter despite providing the type

I'm trying to specify a function parameter as a generic type T:
enum MyEnum {
Foo,
Bar
}
class DbColumn {
final Function<T>(T value) serializer;
const DbColumn({this.serializer});
}
class MyClass {
static final DbColumn rating = DbColumn(
serializer: <MyEnum>(v) {
var i = v.index;
}
);
}
However when trying to access index on v I get this type error message:
The getter 'index' isn't defined for the type 'Object'.
Try importing the library that defines 'index', correcting the name to the name of an existing getter, or defining a getter or field named 'index'.
When I hover over v in VSC it says that it's of type MyEnum.
If I instead remove the generic type and do a cast like this it works as expected:
class DbColumn {
final Function(dynamic value) serializer;
const DbColumn({this.serializer});
}
class MyClass {
static final DbColumn rating = DbColumn(
serializer: (v) {
var casted = v as MyEnum;
var i = casted.index;
}
);
}
Why is the generic type not working as expected?
EDIT:
What is even weirder is that this example works too if I put it inside MyClass:
x<T>(Function(T) c) {}
y() {
x<MyEnum>((v) {
print(v.index); // No error given and type of v is MyEnum
});
}
EDIT 2: The same problem happens when overriding methods:
abstract class MyInterface {
int someFunction<T>(T value);
}
class MyClass implements MyInterface {
#override
someFunction<MyEnum>(v) {
return v.index; // Gives same error and no intellisense happens in VSC
}
}
Instead of making the function generic, declare the class as generic and it will work as expected. Like this :
enum MyEnum {
Foo,
Bar
}
class DbColumn<T> {
final Function(T value) serializer;
const DbColumn({this.serializer});
}
class MyClass {
static final DbColumn<MyEnum> rating = DbColumn(
serializer: (v) {
var i = v.index;
print('Index : $i');
}
);
}
void main() {
MyClass.rating.serializer(MyEnum.Bar);
}
OUTPUT :
Index : 1

Binding between an Object and a SimpleIntegerProperty

I have a combo box over my GUI in JavaFX.
This Combo Box is composed of a complex type elements :
public class DureeChoiceBoxElement extends ObservableValueBase<DureeChoiceBoxElement> {
private IntegerProperty duree;
#Override
public String toString() {
return duree.get() + " an";
}
}
I want to map (or bind) the selected complex element with my model which contains the simple type :
public class Pel {
private IntegerProperty duree = new SimpleIntegerProperty(1);
public Property<Number> dureeProperty() {
return duree;
}
public void setDuree(Integer duree) {
this.duree.setValue(duree);
}
public Integer getDuree() {
return duree.getValue();
}
}
How to do it ?
I tried in the controller with :
public class PelController {
#FXML
private ChoiceBox<DureeChoiceBoxElement> duree;
//etc..
pel.dureeProperty().bind(createElapsedBindingByBindingsAPI2(duree.getValue()));
/*
* #return an ObjectBinding of immutable TimeElapsed objects for the player
*/
private ObjectBinding<Property<Number>> createElapsedBindingByBindingsAPI2(
final DureeChoiceBoxElement dureeChoiceBoxElement) {
return Bindings.createObjectBinding(new Callable<Property<Number>>() {
#Override
public IntegerProperty call() throws Exception {
return dureeChoiceBoxElement.dureeProperty();
}
}, dureeChoiceBoxElement.dureeProperty());
}
}
But it doesn't work (even not compile). I want to say that "Bind this simple property to this complex Object calling the method I give you through the method named "createElapsedBindingByBindingsAPI2(..)".
It is logical read but I didn't managed to make it works anyway.
That's poor ....
Any help please :).
Example that (obviously) works with legacy code style (Swing coding) :
duree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<DureeChoiceBoxElement>() {
#Override
public void changed(ObservableValue<? extends DureeChoiceBoxElement> observable,
DureeChoiceBoxElement oldValue, DureeChoiceBoxElement newValue) {
// changement durée
log.debug("Durée sélectionnée : {}", duree.getSelectionModel().getSelectedItem().getDuree());
log.debug("Durée bindée ? : {}", pel.getDuree());
pel.setDuree(duree.getSelectionModel().getSelectedItem().getDuree());
}
});
Like this my model is set to selected item. But it implies some boilerplate code. Any better idea based on high level bindings of JavaFX ?

Writing a size() method for a User-defined Stack Class

I'm writing a program that requires the length/size of a stack. Because I am not importing the Stack class (and I've made my own - see below) I don't know how to make a method that calculates the size of the stack and returns that integer value. Here's the Stack class so far:
public class Stack<String> implements StackInter<String>
{
public void push(String x)
{ // This method is written
}
public String pop()
{ // This method is written
}
public boolean isEmptyStack()
{ // This method is written
}
public String peek()
{ // This method is written
}
public int size()
{
// What goes in here!
}
}
This is where I want to use the size method
public class InfixCalculator
{
Stack<String> stack = new Stack<String>();
int size = stack.size();
}
Any suggestions would be greatly appreciated!
the pseudo code is somthing like this:
public class Stack<String> implements StackInter<String>
{
private size;
//constructor
public Stack<String>(){
size=0;
}
public void push(String x)
{ // This method is written
size++;
}
public String pop()
{ // This method is written
if(size > 0 )
size--;
}
public boolean isEmptyStack()
{ // This method is written
}
public String peek()
{ // This method is written
}
public int size()
{
int theSize=size;
return theSize;
}
}
after you apply your operations the size can be computed.
If your Stack is an array write
public int size() {
return array.length;
}

How do I initialize a final field in constructor's body?

Basically, that's what I'm trying to do:
ClassName
{
final OtherClass field;
ClassName()
{
field = new OtherClass(this);
}
}
It's not possible to assign a final field in a constructor body. The final field needs to be assigned before the constructor body, in the initializer list or on declaration:
class ClassName
{
final OtherClass field = new OtherClass(); // Here
ClassName()
: field = new OtherClass() // or here
{
}
}
As you can't use this in the initializer list or on the declaration, you can't do what you plan to do.
With null safety, you can initialize a final field in different ways:
At declaration:
class Foo{
final int bar = 1;
}
In constructor parameter (initializing formal).
class Foo {
final int bar;
// Initializing in constructor parameter.
Foo(this.bar);
}
In the initializer list.
class Foo {
final int bar;
// Initializer list
Foo() : bar = 1;
}
Combination of above two.
class Foo {
final int bar;
Foo(int value) : bar = value;
}
Use late keyword for lazy initialization.
class Foo {
late final int bar; // Initialize it later, maybe in a method
}
Since Dart 2.12 it is possible by using late keyword.
The code below prints 5:
class ClassName
{
final int var1 = 5;
late final OtherClass field;
ClassName()
{
field = new OtherClass(this);
}
}
class OtherClass {
OtherClass(ClassName object) {
print(object.var1);
}
}
void main() {
final object = ClassName();
}
Please see this and the following sections

How to implement Iterable<E>

I am trying to port the Java code below to Dart and am puzzled about to do this.
In Java the Iterable interface is where clean with one method and to implement this is a snap.
How is this code best transformed to Dart?
/**
* Chess squares represented as a bitmap.
*/
public class ChessSquares implements Iterable<ChessSquare> {
private static class ChessSquaresIterator implements Iterator<ChessSquare> {
long bits;
int nextBit;
public ChessSquaresIterator(long bits) {
this.bits = bits;
nextBit = Long.numberOfTrailingZeros(bits);
}
#Override
public boolean hasNext() {
return (nextBit < 64);
}
#Override
public ChessSquare next() {
ChessSquare sq = ChessSquare.values()[nextBit];
bits = bits & ~sq.bit;
nextBit = Long.numberOfTrailingZeros(bits);
return sq;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
#Override
public Iterator<ChessSquare> iterator() {
return new ChessSquaresIterator(bits);
}
...
By using IterableMixin you only need to implement the iterator-function.
class ChessSquares with IterableMixin<ChessSquare> {
#override
Iterator<ChessSquare> get iterator => new ChessSquaresIterator(bits);
...
}
Visit http://blog.sethladd.com/2013/03/first-look-at-dart-mixins.html for a short introduction on mixins.
The Iterator-interface is straight forward. You only have to implement the function moveNext and the getter current.
Soo I tried this which is kind of not what I want since I do not want to extend a base class.
/**
* Chess squares represented as a bitmap.
*/
class ChessSquares extends IterableBase<ChessSquare> {
Iterator<ChessSquare> get iterator {
return new ChessSquaresIterator(this);
}
...
}
class ChessSquaresIterator extends Iterator<ChessSquare> {
int _nextBit;
int64 _bits;
ChessSquare _current;
ChessSquaresIterator(ChessSquares squares) {
_bits = new int64.fromInt(squares._bits);
}
bool moveNext() {
_nextBit = _bits.numberOfTrailingZeros();
if (_nextBit < 64) {
_current = ChessSquare.values()[_nextBit];
_bits = _bits & ~_current.bit();
} else {
_current = null;
}
return _nextBit < 64;
}
E get current => _current;
}

Resources