Java assignment from parameter or instance variable - java

In terms of programming style, which of the following two options is better?
Option 1
public class A {
private int x, y;
public A (int z) {
this.x = z
this.y = this.x
}
}
Option 2
public class A {
private int x, y;
public A (int z) {
this.x = z
this.y = z
}
}

Both are same...
But i think if you look at code option 2 looks better because you dont even have to rad it to understand
why make things complected, if there is no benefit...

Performance wise, I don't think there is any difference. If you really must choose one, I'd go with the second one as it is easier to read and understand.

Related

How to make a class operate with math operation in java? [duplicate]

This question already has answers here:
Operator overloading in Java
(10 answers)
Closed 5 years ago.
I have the following class, which describe one point on XY surface:
class Point{
double x;
double y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
So I want to overlad + and - operators to have possibility write run following code:
Point p1 = new Point(1, 2);
Point p2 = new Point(3, 4);
Point resAdd = p1 + p2; // answer (4, 6)
Point resSub = p1 - p2; // answer (-2, -2)
How can I do it in Java? Or I should use methods like this:
public Point Add(Point p1, Point p2){
return new Point(p1.x + p2.x, p1.y + p2.y);
}
Thanks in advance!
You cannot do this in Java. You'd have to implement a plus or add method in your Point class.
class Point{
public double x;
public double y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public Point add(Point other){
this.x += other.x;
this.y += other.y;
return this;
}
}
usage
Point a = new Point(1,1);
Point b = new Point(2,2);
a.add(b); //=> (3,3)
// because method returns point, you can chain `add` calls
// e.g., a.add(b).add(c)
Despite you can't do it in pure java you can do it using java-oo compiler plugin.
You need to write add method for + operator:
public Point add(Point other){
return new Point(this.x + other.x, this.y + other.y);
}
and java-oo plugin just desugar operators to these method calls.
There is no operator overloading in Java. Apparently for reasons of taste. Pity really.
(Some people will claim that Java does have overloading, because of + with String and perhaps autoboxing/unboxing.)
Let's talk about value types.
Many early classes (and some later ones) make a right mess of this. Particularly in AWT. In AWT you should be explicitly making copies of simple values all over the place. Almost certainly you want to make value types immutable - the class should be final and it should never change state (generally all final fields pointing to effective immutables).
So:
public final class Point {
private final int x;
private final int y;
private Point(int x, int y) {
this.x = x;
this.y = y;
}
public static of(int x, int y) {
return new Point(x, y);
}
public int x() {
return x;
}
public int y() {
return y;
}
public Point add(Point other) {
return of(x+other.x, y+other.y);
}
// Standard fluffy bits:
#Override public int hashCode() {
return x + 37*y;
}
#Override public boolean equals(Object obj) {
if (!(obj instanceof Point)) {
return false;
}
Point other = (Point)obj;
return x==other.x && y==other.y;
}
#Override public String toString() {
return "("+x+", "+y+")";
}
}
The original code was confused between int and double, so I've chosen one. If you used double you should exclude NaN. "Point" tends to imply an absolute point, which doesn't make sense to add. "Vector" or "dimension" would probably be more appropriate, depending upon what you intend.
I've hidden the constructor, as identity is not important. Possibly values could be cached. Possibly it is, say, common to add a point to a zero point, so no points need to be created.
It's possible you might want a mutable version, for example to use as an accumulator. This should be a separate class without an inheritance relationship. Probably not in simple cases, but I'll show it anyway:
public final class PointBuilder {
private int x;
private int y;
public PointBuilder() {
}
public PointBuilder(Point point) {
this.x = point.x;
this.y = point.y;
}
public Point toPoint() {
return new Point(x, y);
}
public PointBuilder x(int x) {
this.x = x;
return this;
}
public PointBuilder y(int y) {
this.y = y;
return this;
}
public PointBuilder add(Point other) {
this.x += other.x;
this.y += other.y;
return this;
}
}
You cannot do this in Java because there is no operator overloading in Java.
You have to use the second option you have mentioned:
Edit: You can add the Add method in the Point class itself
public Point Add(Point other){
return new Point(this.x + other.x, this.y + other.y);
}
You cannot overload operators in java. You will need handle this in Point class.
You cannot override operators in Java. That's one of the reasons why any nontrival math (especially geometric) operations should not be implemented in Java (the Point class above is kind of such a class, if you want it to do some real work, for example a line-line intersection, you'd better do it in C++).

Is it possible to retrieve x or y without altering Pos class

I'm working on a homework assignment regarding a maze of boolean values. The goal is basically to find the shortest path from start to finish if it exists. That's something I think I can handle. But!
We have been given a class called Pos that handles positions in the maze. And this is where my question comes in:
This is the class:
public class Pos implements Comparable<Pos>{
public int x, y;
Pos(int x, int y){
this.x = x;
this.y = y;
}
public int compareTo(Pos p){
return (this.x != p.x ? this.x - p.x : this.y - p.y);
}
}
The maze solver is gonna be like this:
public ArrayList<Pos> solve(Pos start, Pos finish, boolean maze[][])
Now what I was thinking about doing is getting the coordinates from start and finish and store them in variables when searching through the maze. Like startX and startY.
But here's the problem. I am wondering if this is possible without altering the Pos class? I'm not sure if I'm allowed to add getX() and getY() to the Pos class.
Any help is appreciated.

What type collection use for sorted unique object in Java?

I have simple object:
public class Vector3i {
public int x, y, z;
public Vector3i(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
}
What collection I need for sorted unique items?
Thank you for your help and advice.
To sort unique object in java you're going to want to create you're own comparator.
Using comparator to make custom sort

Java - Edit instance variables without a method

I am quite new to Java, and I am constantly looking for ways to improve my code. But I don't seem to get this, if it is even possible to do.
Let's say I have this code (I edited out the irrelevant parts, so the code might seem weird):
public class NewBody {
public static int distanceScale = 5;
public int x, y;
public float xMeter = x * distanceScale;
public float yMeter = y * distanceScale;
public NewBody(int x, int y){
this.x = x;
this.y = y;
}
public void pixToMeter(){
this.xMeter = distanceScale * this.x;
}
If I don't call pixToMeter() and just try to use "instance.xMeter" directly, it just returns the vaulue 0, even though I've already set the x variable in the constructor.
So my question is: Is there a way to properly set variables without calling a method to do it? It seems highly unneccessary since I am not even passing a parameter to it.
Sorry for my poor english, I hope you understand what I am trying to say.
The initialisation of xMeter is done when x is still zero.
This is what actually happens:
public NewBody(int x, int y) {
// All fields are zeroed: 0, null, 0.0.
super(); // Object constructor, as Object is the parent class.
// Those fields that are initialized:
xMeter = this.x * distanceScale; // 0.0f * 5
yMeter = this.y * distanceScale;
// The rest of the constructor:
this.x = x;
this.y = y;
}
For a depending value:
public final void setX(int x) {
this.x = x;
xMeter = this.x * distanceScale;
}
And to apply the DRY principle (Don't Repeat Yourself): one could drop the initialisation of xMeter and call setX(x) in the constructor instead.
When called in the constructor it is important to make setX final, that is: not overridable.
The source of the problem is here:
public float xMeter = x * distanceScale;
The issue is that you're initializing this instance variable outside the constructor. As a result, since x is initialized to 0, the result of your multiplication is also 0.
If you need xMeter and yMeter initialized to a value based on x or y, simply declare them as you did the other fields:
public int xMeter;
And initialize their values in the constructor:
public newBody(int x, int y){
// initialize x and y ...
this.xMeter = x * distanceScale;
As others have mentioned, when the xMeter is initialized, the constructor is not called yet and x is still 0, so the value of xMeter is 0 as well.
To change that, you must update xMeter's value once x is initialized in the constructor, like so:
public NewBody(int x, int y){
this.x = x;
this.y = y;
// update x and y meter
xMeter = x * distanceScale;
yMeter = y * distanceScale;
}
However, you mentioned how you want xMeter to update every time x is changed as well. As it stands with your current code, that will not happen. However, a suggestion of mine would be to create a method to change the value of x (and y as well) and in those methods, also update the values of xMeter and yMeter. That way, whenever you want to change x, call the methods and it will update your other values too.
Try adding these methods and changing your constructor to this:
// called setter methods
public void setX(int x) {
this.x = x;
this.xMeter = x * distanceScale;
}
public void setY(int y) {
this.y = y;
this.yMeter = y * distanceScale;
}
// constructor
public NewBody(int x, int y){
setX(x);
setY(y);
}

How to get a value from an array to be used in another class?

If there is an array such as:
//....
int[] anArray;
anArray = new int[3];
anArray[0] = new otherClassWConst( x, y , z);
anArray[1] = new otherClassWConst( x, y , z);
anArray[2] = new otherClassWConst( x, y , z);
//....
With the values of x and y and z all being of different value to the other x, y, and z's from the other objects in the array. (Does that make sense? Like the value of x in anArray[0] is not the same as the value found in anArray[2]). Note: there is a constructor from another class that requires those parameters, I'm not sure if thats important
How do I, in a different class, get the value of one of the parameters (for example, the value of y) in each of the array values. As in, is there a way I can get all three values of the Ys so I can add them all up together in another class?
For example
//code attaining only the y values of the array
overallValueOfY = Y + Y + Y; // or something of that nature
//life continues over here.
Please tell me if something is unclear, I tried so hard to explain. Thank you for the consideration.
OtherClassConst will need to supply a get method for it:
public class OtherClassConst {
private int x;
private int y;
private int x;
public (int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int getY() {
return y;
}
/* Same concept for getX() and getZ() */
}
Then, you class can call it:
int sumY = 0;
for (OtherClassConst c : myArray) {
sumY += c.getY();
}
First off, your array won't work unless your new class extends Int, I just want to make sure you know that.
Now, all you have to do is in that new class create an int varriable
int x;
int y;
int z;
and set them equal to what is put in the constructor. Then create a new method that returns the values
public int getX(){
return this.x;
}
public int getY(){
return this.Y;
}
public int getZ(){
return this.Z;
}
You need to create POJO for your other class with x,y and z instance variables, then using setter method of y you can get the values. Iterate over them to get the sum of values.
If you other OtherClass has a getY method that returns an integer then you can use the following to sum them:
Arrays.stream(anArray).mapToInt(OtherClass::getY).sum();
It is worth getting use to using streams rather than for loops.

Categories

Resources