Multithreading private constructor - java

Straight out from Java concurrency in Practice :
#ThreadSafe
public class SafePoint {
#GuardedBy("this") private int x, y;
private SafePoint(int[] a) { this(a[0], a[1]); }
public SafePoint(SafePoint p) { this(p.get()); }
public SafePoint(int x, int y) {
this.x = x;
this.y = y;
}
public synchronized int[] get() {
return new int[] { x, y };
}
public synchronized void set(int x, int y) {
this.x = x;
this.y = y;
}
}
The above is a Thread-safe class : since its setters are synchronized.
I understand also why the getter doesn't individually return x / y but instead returns an array.
I have 2 questions .
Why ?
private SafePoint(int[] a)
public SafePoint(SafePoint p) { this(p.get()); } instead of this(p.x,p.y);

Because calling this(p.x, p.y) is not atomic. In other words, imagine the following thread interleaving:
Thread1: read p.x
Thread2: p.set(otherX, otherY);
Thread1: read p.y and call this(p.x, p.y);
The x and the y are now from two different points and possibly not consistent.
On the other hand, p.get() reads x and y atomically (it is synchronized) and therefore guarantees that the x and the y in the array are from the same point.

Related

Java super set private fields

I'm learning java inheritance and encapsulation. Here is sample code
class Base {
private int x;
private int y;
Base(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
class Child extends Base {
Child(int x, int y) {
super(x, y);
}
}
Child c = new Child(1, 2);
System.out.println(c.getX());
Why have I access to x and y (private) in Child class? Does super change anything?
You don't have access to x and y in Child class. When you write
Child(int x, int y) {
super(x, y);
}
the x and y are formal parameters of Child's constructor, that happen to be called the same names as private fields x and y of the superclass. They might as well be called something else - say, a and b, and the effect would be exactly the same:
Child(int a, int b) {
super(a, b);
}
Why have I access to x and y (private) in Child class?
you dont, if you would you could do without problem:
System.out.println(c.x);
System.out.println(c.y);
you wrote instead public setters/getters that are giving you access (capsulation) to the fields..

Java Algorithm for finding shortest distance between 2d point and Matrix

I'm stuck on this question for a couple of days now and would really like to get some help.
I am given a 2 dimensional point in the range of (0-1 not including 1), such as (0.5,0.2), and N other points (also in the range of 0-1).
The first part of the question is to implement the "dumb" algorithm, which when given a certain point will find the point with the shortest distance from it, which has a complexity of O(N).
The part I'm stuck at, requires to build a Matrix K on K, where each "cell" will contain the points that belong to that cell. Once done, when given the original point I will need to search for the point with the shortest distance to it only in some of the cells and not the entire Matrix, which should result better complexity.
My original thought is to devide the points so that each block will have an arraylist of points that belong to him, and then to somehow go through the main block(the one that the original point belongs to) and continue by going through it's neighbors, however implementing it hasn't been very successful.
I would highly appreciate any help/ advice.
Below is what I currently have:
public class Point {
private double x;
private double y;
private Block b;
public Point(double x, double y)
{
this.x=x;
this.y=y;
}
public Point(double x, double y, Block b) //consrtuctor for complex case
{
this.x=x;
this.y=y;
b.points.add(this);
}
public double getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public double distance(Point p)
{
double res=0;
res = Math.sqrt(Math.pow(this.x-p.getX(),2)+Math.pow(this.y-p.getY(),2));
return res;
}
}
import java.util.ArrayList;
public class Block {
private int x;
private int y;
public ArrayList<Point> points;
public Block(int x, int y) {
points = new ArrayList<Point>();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
import java.util.Random;
public class ComplexCase {
private Block[][] blockMat;
public ComplexCase(int k, int n)
{
Random generator = new Random();
Point p1;
Block b1;
double x,y;
int bx1,by1;
int t;
t = 1/k;
blockMat = new Block[k][k];
for (int i =0;i<n;i++)
{
x = generator.nextDouble();
y = generator.nextDouble();
bx1 = (int) (x/t);
by1 = (int) (y/t);
b1 = new Block(bx1,by1);
p1 = new Point(x,y,b1);
}
}
public Block[][] getBlockMat() {
return blockMat;
}
public void setBlockMat(Block[][] blockMat) {
this.blockMat = blockMat;
}
}

toString() method not printing the correct values of object

I'm following a book and I have a Point class which defines a point and I am trying to display the values. I've been looking around for a while now, whatever I do it always displays [0,0] here's my code.
class Main {
public static void main(String []args) {
Point point = new Point(10, 20);
System.out.println(point.toString());
}
}
class Point {
private int x, y;
public Point(int x, int y) {
x = x;
y = y;
}
public String toString() {
return "[" + x + ", " + y + "]";
}
You're never initializing class members x and y actually. So they're initialized as 0 automatically hence the [0,0] output.
x = x means parameter x = parameter x which does nothing.
use this.x = x; instead so Point class member x will be set.
Look at your constructor:
public Point(int x, int y) {
x = x;
y = y;
}
In your case you do not initialize class fields. To do that, use this keyword and it should look like:
public Point(int x, int y) {
this.x = x;
this.y = y;
}
Otherwise you are dealing with parameter x and y variables only.
Use this in Constructor as below :-
class Point {
private int x, y; // These x and y are member of Point class
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "[" + x + ", " + y + "]";
}
You are not initializing x and y of Point class.
In toString() method you are printing x and y of Point class which are not initialized and hence taking default value of 0 i.e. 0 is default value of integer.
use the this keyword for the separation of local variable and instance variable. in your parameterized constructor jvm is not able to initialize the instance variable because it gets an ambiguity problem between local and instance variable. And instance variable in java gets implicitly initialized if u we are not initializing that's why you are getting [0,0] as the output.
here is the code..
class Main {
public static void main(String []args) {
Point point = new Point(10, 20);
System.out.println(point.toString());
}
}
class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "[" + x + ", " + y + "]";
}
In your Constructor for the Point object:
public Point(int x, int y) {
this.x = x;
this.y = y;
}
You will need to put this.x to indicate you are setting the value of the Point object's x variable, not the x argument passed into the constructor.
The updated, functional code is below:
class Main {
public static void main(String []args) {
Point point = new Point(10, 20);
System.out.println(point.toString());
}
}
class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "[" + x + ", " + y + "]";
}

method issue in java

i'm learning to create custom classes and can't figure out where I've gone wrong
From main class...
MyPoint p1 = new MyPoint(317, 10);
the error says:
constructor MyPoint in class MyPoint cannot be applied to given types;
required: no arguments
found: int, int
reason: actual and formal argument lists differ in length
this is from my MyPoint class:
private int x, y;
public void MyPoint(int x, int y)
{
this.x = x;
this.y = y;
}
Why isn't MyPoint(317, 10) being fed into the relevant class along with the x and y values?
Any help would be appreciated, thank you.
Constructors don't have return type. This is just a normal method you just made.
Solution: Remove the void from the method. It should look like
public MyPoint(int x, int y)
{
this.x = x;
this.y = y;
}
remove return type from
public void MyPoint(int x, int y)
constructor cannot have return type not even void
make it
public MyPoint(int x, int y)
{
this.x = x;
this.y = y;
}
You need to declare parameterized constructor in MyPoint class.
public MyPoint(int x, int y)
{
this.x = x;
this.y = y;
}
Constructors must not have return type. So change your code as
public MyPoint(int x, int y)
{
this.x = x;
this.y = y;
}

Static Vector Multiply - No New Objects

Is there a way to have a static method such that it returns a Vector object (with a simple integer x and y value as fields) which is a Vector multiplied by an int value argument. However, there are no new objects made, i.e, the object assigned to the return value is changed instead of there being a new Vector created?
The following code does not achieve this:
public class Vector{
public int x,y;
public Vector(int x,int y){
this.x = x;
this.y = y;
}
//Important code starts
public static Vector mult(Vector v,int a){
return new Vector(v.x*a,v.y*a);
}
//Important code stops
}
This code is what I'm after but it's too messy:
public static Vector mult(Vector v1,Vector v2,int a){
v1.x = v2.x*a;
v1.y = v2.y*a;
}
Is there an alternative?
Why not add:
public void multiply(Vector otherVector, int a){
x = otherVector.x * a;
y = otherVector.y * a;
}
to your Vector class.
Do you mean?
public void mult(double a) {
x *= a;
y *= a;
}

Categories