Method that always return null - java

I'm stuck with a piece of a code I'm translating from Java to C#.
Basically, I have a Map(Dictionary) with keys composed by Pair and Values represented by a class made by me (Square); in this class there's only one field, which is Optional (yes, I create the Optional class in C#).
At the beginning I fill this Dictionary with pairs to make a simil-grid and empty Optional, as you can see in the code below.
class World
{
private Dictionary<Pair<int, int>, Square> map =
new Dictionary<Pair<int, int>, Square>();
public World(int width, int height)
{
this.size = new Pair<int, int>(width, height);
for (int w = 0; w < this.size.GetX(); w++)
{
for (int h = 0; h < this.size.GetY(); h++)
this.map.Add(new Pair<int, int>(w, h),
new Square(Optional<Entity>.Empty()));
}
}
}
And this is the Square class
class Square
{
private Optional<Entity> entity;
public Square (Optional<Entity> entity)
{
this.entity = entity;
}
public Optional<Entity> GetEntity()
{
return this.entity;
}
public void SetEntity(Optional<Entity> entity)
{
this.entity = entity;
}
}
Here's the problem, this function below always returns null when I try to get an existent value from the Dictionary, it throws System.NullReferenceException: Object reference not set to an instance of an object.
In this code I cut away all the controls, but I know that I try to get a value already inserted; also, I tried to run Dictionary.ContainsValue and it return false! But I do have inizialed the Dictionary.
public Square? GetSquare(int x, int y)
{
if (y < this.size.GetY() && y >= 0 && < x this.size.GetX() && x >= 0)
{
this.map.TryGetValue(new Pair<int, int>(x, y), out Square? square);
return square;
}
throw new InvalidOperationException("no square in this position!");
}
I leave here the code of the Optional class too, but I'm almost 100% sure that it's not the problem
public class Optional<T>
{
private T value;
public bool IsPresent { get; set; } = false;
private Optional() { }
public static Optional<T> Empty()
{
return new Optional<T>();
}
public static Optional<T> Of(T value)
{
Optional<T> obj = new Optional<T>();
obj.Set(value);
return obj;
}
private void Set(T value)
{
this.value = value;
this.IsPresent = true;
}
public T Get()
{
return value;
}
}
This is Pair class
public class Pair<X, Y>
{
private X first;
private Y second;
public Pair(X first, Y second)
{
this.first = first;
this.second = second;
}
public X GetX()
{
return this.first;
}
public Y GetY()
{
return this.second;
}
public override string ToString()
{
return "<" + first + "," + second + ">";
}
}

Ok, solved it.
The problem was, as you said, the Pair class.
I substitute it with the ValueTuple<> class and now everything works fine, still thanks.

Related

why default method not recognized as property(getter/setter)?

Interface:
public interface SomeInt{
Integer getX();
void setX(Integer value);
default Integer getY(){
return getX();
}
default void setY(Integer value){
setX(value);
}
}
A Class implement it:
public class A implements SomeInt{
private Integer x;
public Integer getX(){
return x;
}
public void setX(Integer value){
x = value;
}
}
When initialized, I can call the method getY & setY, and get the right return.
But I cannot use it in JSP(EL), like ${instance_of_class_a.y}. And the property Y is not list in IDEA's variables list(Debug Mode).
If I do add the getY & setY explicitly in class A, everything is ok.
Why? I think default method is like a compiler sugar.
Sorry for my poor english and the mistakes in the code, I've correct it.
The question is a bit ill written here, so maybe something went wrong.
Especially add #Override for typos.
interface SomeInt {
int getX();
void setX(int x);
default int getY() {
return getX();
}
default void setY(int value) {
setX(value);
}
}
static class A implements SomeInt {
private int x;
#Override
public int getX() {
return x;
}
#Override
public void setX(int value) {
x = value;
}
}
System.out.println("Methods:");
for (Method m : A.class.getMethods()) {
System.out.printf("+ %s%n", m.getName());
}
for (Method m : A.class.getDeclaredMethods()) {
System.out.printf("- %s%n", m.getName());
}
In general for getters/setters Class.getMethods is used.
Methods:
+ setX
+ getX
...
+ setY
+ getY
- setX
- getX
I think I've got the answer.
BeanELResover using java.beans.Introspector to getBeanInfo(Properties)
public static BeanInfo getBeanInfo(Class<?> beanClass)
throws IntrospectionException
{
if (!ReflectUtil.isPackageAccessible(beanClass)) {
return (new Introspector(beanClass, null, USE_ALL_BEANINFO)).getBeanInfo();
}
ThreadGroupContext context = ThreadGroupContext.getContext();
BeanInfo beanInfo;
synchronized (declaredMethodCache) {
beanInfo = context.getBeanInfo(beanClass);
}
if (beanInfo == null) {
beanInfo = new Introspector(beanClass, null, USE_ALL_BEANINFO).getBeanInfo();
synchronized (declaredMethodCache) {
context.putBeanInfo(beanClass, beanInfo);
}
}
return beanInfo;
}
The constructor of Introspector call a method "findExplicitBeanInfo" to getDeclaredMethods of current class. Then do it with its superClass until Object or stopClass. The method of interfaces will not be loaded here.
private Introspector(Class<?> beanClass, Class<?> stopClass, int flags)
throws IntrospectionException {
this.beanClass = beanClass;
// Check stopClass is a superClass of startClass.
if (stopClass != null) {
boolean isSuper = false;
for (Class<?> c = beanClass.getSuperclass(); c != null; c = c.getSuperclass()) {
if (c == stopClass) {
isSuper = true;
}
}
if (!isSuper) {
throw new IntrospectionException(stopClass.getName() + " not superclass of " +
beanClass.getName());
}
}
if (flags == USE_ALL_BEANINFO) {
explicitBeanInfo = findExplicitBeanInfo(beanClass);
}
Class<?> superClass = beanClass.getSuperclass();
if (superClass != stopClass) {
int newFlags = flags;
if (newFlags == IGNORE_IMMEDIATE_BEANINFO) {
newFlags = USE_ALL_BEANINFO;
}
superBeanInfo = getBeanInfo(superClass, stopClass, newFlags);
}
if (explicitBeanInfo != null) {
additionalBeanInfo = explicitBeanInfo.getAdditionalBeanInfo();
}
if (additionalBeanInfo == null) {
additionalBeanInfo = new BeanInfo[0];
}
}

Interface and type casting

In the Java 8 tutorial about interface, one example says that when a class implements an interface, one has to type cast the interface type into the class type in order to invoke methods of this class, as shown by the following example from the java 8 tutorial:
public class RectanglePlus
implements Relatable {
public int width = 0;
public int height = 0;
public Point origin;
// four constructors
public RectanglePlus() {
origin = new Point(0, 0);
}
public RectanglePlus(Point p) {
origin = p;
}
public RectanglePlus(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public RectanglePlus(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
// a method for moving the rectangle
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}
// a method for computing
// the area of the rectangle
public int getArea() {
return width * height;
}
// a method required to implement
// the Relatable interface
public int isLargerThan(Relatable other) {
RectanglePlus otherRect
= (RectanglePlus)other;
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea() > otherRect.getArea())
return 1;
else
return 0;
}
}
In the method isLargerThan(Relatable other), other is casted to type RectanglePlus in order to invoke getArea().
In the other example about default methods in interface, the compareTo(Card o) method doesn't type cast o to type PlayingCard, but can invoke int hashCode() directly, I don't understand this. Thanks for your help.
package defaultmethods;
public class PlayingCard implements Card {
private Card.Rank rank;
private Card.Suit suit;
public PlayingCard(Card.Rank rank, Card.Suit suit) {
this.rank = rank;
this.suit = suit;
}
public Card.Suit getSuit() {
return suit;
}
public Card.Rank getRank() {
return rank;
}
public boolean equals(Object obj) {
if (obj instanceof Card) {
if (((Card)obj).getRank() == this.rank &&
((Card)obj).getSuit() == this.suit) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public int hashCode() {
return ((suit.value()-1)*13)+rank.value();
}
public int compareTo(Card o) {
return this.hashCode() - o.hashCode();
}
public String toString() {
return this.rank.text() + " of " + this.suit.text();
}
public static void main(String... args) {
new PlayingCard(Rank.ACE, Suit.DIAMONDS);
new PlayingCard(Rank.KING, Suit.SPADES);
}
}
In short: Because hashCode is defined in java.lang.Object and every other class extends Object implicitly.
So when you have
public int compareTo(Card o) {
return this.hashCode() - o.hashCode();
}
the compiler already knows that o is of type Card which extends Object which defines a hashCode method. No need for an explicit cast.
On the other hand in your isLargerThan method the parameter is of type Relatable:
public int isLargerThan(Relatable other) {
RectanglePlus otherRect
= (RectanglePlus)other;
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea() > otherRect.getArea())
return 1;
else
return 0;
}
And judging from the link you provided, the getArea method is defined in RectanglePlus only. Since the compiler only sees Relatable it does not know anything about a getArea method at this point and you need to explicitly cast other to RectanglePlus to be able to access it.
Note that you should actually do an instanceof check before casting to avoid a ClassCastException when other is not a RectanglePlus (you don't know if there might be other classes implementing Relatable).
Let me try a non-code related example:
If people have a pet they usually give it a name. So whatever pet you have, one can always ask for its name (cf. hashCode). But they cannot ask you to make it bark (cf. getArea) unless they know that it is a dog.
And you will probably fail to make a cat bark (cf. ClassCastException).

Override Integer compareTo? Or trick it?

I am trying to write a generic heap class.
import java.util.ArrayList;
public class heap<T extends Comparable<T>>
{
private ArrayList<T> h;
private int size;
public heap()
{
h = new ArrayList<T>();
h.add(null);
size = 0;
}
public T getMin()
{
return h.get(1);
}
public T popMin()
{
T tmp = getMin();
h.set(1, h.get(size));
size--;
sift(1);
return tmp;
}
public void insert(T key)
{
h.add(key);
percolate(++size);
}
public int getSize()
{
return this.size;
}
private int getLeftSon(int i)
{
return (i<<1<=size)? i<<1 : 0;
}
private int getRightSon(int i)
{
return ((i<<1)+1<=size)? (i<<1)+1 : 0;
}
private int getFather(int i)
{
return ((i>>1)!=0)? i>>1 : 0;
}
private void swap(int i, int j)
{
T tmp = h.get(i);
h.set(i, h.get(j));
h.set(j, tmp);
}
private void sift(int i)
{
int son;
do {
son = 0;
if (getLeftSon(i) != 0)
{
son = getLeftSon(i);
if (getRightSon(i) != 0 && h.get(getRightSon(i)).compareTo(h.get(getLeftSon(i))) > 0)
son = getRightSon(i);
if (h.get(son).compareTo(h.get(i)) <= 0)
son = 0;
}
if (son!=0) {
swap(i, son);
i = son;
}
} while (son!=0);
}
private void percolate(int i)
{
T key = h.get(i);
while ((i > 1) && (key.compareTo(h.get(getFather(i))) > 0))
{
h.set(i, h.get(getFather(i)));
i = getFather(i);
}
h.set(i, key);
}
}
All good. It works like a charm. Excepting one thing: if I work with Integers I don't have 'access' to the method compareTo from Integer. meaning that I can not override it's behaviour. I will always have a Max heap this way. Can Integer compareTo by override (I don't think it can)?
So what can I do apart from creating another class MyInteger extends Integer{...} and override it there.
You could make your heap accept a Comparator in constructor and then provide a Comparator that reverses the order.
That's what the Comparator is for actually - defining an ordering that's not a natural one for the given class, being able to define multiple orderings of the same class, or indeed defining an ordering for a class you cannot modify.
The approach of accepting a comparator at construction time can be seen in TreeSet for example.
Example code stub:
public class Heap<T> { /* no need for items to extend Comparable anymore */
private final Comparator<T> cmp;
public Heap(Comparator<T> cmp) {
this.cmp = cmp;
...
}
...
}
... and then use cmp.compare(item1, item2) wherever you now use item2.compareTo(item2).

Add a condition to an if statement based on only one of the different parameters of an object

I created a digraph using the jgrapht library, and it takes as vertices Pointobjects I created. These objects take as parameters two coordinates and a type. I made a simple and short example:
public static DirectedGraph<Point, DefaultEdge> directedGraph = new DefaultDirectedGraph<Point, DefaultEdge>(DefaultEdge.class);
public static Point firstPoint = new Point(2, 7, "A");
public static Point secondPoint = new Point(2, 8, "B");
public static Point thirdPoint = new Point(2, 9, "B");
public static Point fourthPoint = new Point(2, 4, "C");
void setup () {
directedGraph.addVertex(firstPoint);
directedGraph.addVertex(secondPoint);
directedGraph.addVertex(thirdPoint);
directedGraph.addVertex(fourthPoint);
directedGraph.addEdge(firstPoint, secondPoint);
directedGraph.addEdge(secondPoint, thirdPoint);
directedGraph.addEdge(secondPoint, fourthPoint);
int degree = directedGraph.outDegreeOf(secondPoint);
if (degree >= 2) {
for (Point successor : Graphs.successorListOf (directedGraph, secondPoint)) {
if (/*the iD is equal to B*/){
for (Point predecessor : Graphs.predecessorListOf (directedGraph, secondPoint )) {
directedGraph.addEdge(predecessor, successor);
}
}
}
}
// --------------------------------------------------------------
public static ArrayList<Point> pointList = new ArrayList<Point>();
public static class Point {
public int x;
public int y;
public String iD;
public Point(int x, int y, String iD)
{
this.x = x;
this.y = y;
this.iD= iD;
}
#Override
public String toString() {
return ("[x="+x+" y="+y+" iD="+iD+ "]");
}
#Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + this.x;
hash = 71 * hash + this.y;
return hash;
}
#Override
public boolean equals(Object other)
{
if (this == other)
return true;
if (!(other instanceof Point))
return false;
Point otherPoint = (Point) other;
return otherPoint.x == x && otherPoint.y == y;
}
}
I'd like to add a condition in the if statement on the iD of the vertices, but not on the two other parameters of my Point objects. Is there a way to do this ?
If I understand your question, then yes it's possible. Use the public iD field. Something like,
for (Point successor : Graphs.successorListOf (directedGraph, secondPoint)) {
// if (/*the iD is equal to B*/){
if (successor.iD.equals("B")){
// ...
}
}
You've defined it as a public field. You can access it by using . Just do:
if (successor.iD.equals("B")) {
See: Oracle Tutorial on Class Members

Mirroring function with apache commons

How do you mirror a function on x-Axis in Apache commons math, respectively set f() = -f()?
I found out so far, that you can add functions with FunctionUtils class and i guess i could
do a workaround by taking some points, set y-values negativ and interpolationg new Function,
but that seems a little cumbersome to me. Is there a simpler way?
As all functions are interfaces in org.apache.commons.math3.analysis you can wrap every function you want to invert into an anonymous object implementing that interface.
Here are three examples which should get you started:
/**
* Created for http://stackoverflow.com/q/22929746/1266906
*/
public class MinusFunction {
public static BivariateFunction invert(final BivariateFunction function) {
return new BivariateFunction() {
#Override
public double value(double x, double y) {
return - function.value(x,y);
}
};
}
public static MultivariateFunction invert(final MultivariateFunction function) {
return new MultivariateFunction() {
#Override
public double value(double[] point) {
return -function.value(point);
}
};
}
public static MultivariateMatrixFunction invert(final MultivariateMatrixFunction function) {
return new MultivariateMatrixFunction() {
#Override
public double[][] value(double[] point) {
final double[][] value = function.value(point);
for (int i = 0; i < value.length; i++) {
for (int j = 0; j < value[i].length; j++) {
value[i][j] = -value[i][j];
}
}
return value;
}
};
}
}

Categories