I have a setter that has two parameters like so
public void setStuff(OBJECT x, OBJECT, y)
If the value of the x is greater than the y I want to set the value of x to BLAH_BLAH and y to FINAL_THING. How would I do this since they are objects and all I know is to check if they are equal. with the equals method.
For comparing objects I would suggest you to override equals method and in equals compare on the variable
This is a simple class CompareObject
public class CompareObjects {
public int age;
public static void main(String args[])
{
CompareObjects co=new CompareObjects();
co.age=10;
CompareObjects co1=new CompareObjects();
co1.age=100;
System.out.println(co.equals(co1));
}
public boolean equals(CompareObjects co)
{
if(this.age>co.age)
return true;
else return false;
}
}
output false
Now you know which object is greater than which object.
Now you use this method in your public void setStuff(OBJECT x, OBJECT, y)
For example
public void setStuff(OBJECT x, OBJECT, y)
{
if(x.equals(y)
{
//do something
}
else
{
//do something
}
}
If you know how to get the values of x and the value of y, then do this:
pseudo java:
if (getValue of x > getValue of y),
x.setValue = xyz,
y.setValue = abc.
Related
I have an ArrayList containing objects which have 4 parameters (x, y, iD and myType). I want to verify if there are objects in this ArrayList which have particular coordinates, independently of their iD and myType parameters.
I wanted to use Arrays.asList(yourArray).contains(yourValue) but it is when the object has only one parameter.
Here is the whole code:
public class MyObject {
public float x;
public float y;
public int iD;
public String myType;
public MyObject (float x, float y, int iD, String myType)
{
this.myType = myType;
this.iD = iD;
this.x = x;
this.y = y;
}
#Override
public String toString() {
return ("[iD="+iD+" x="+x+" y="+y +" type="+myType+"]");
}
}
ArrayList<MyObject> myArrayList = new ArrayList<MyObject>();
void setup()
{
size(100, 60);
myArrayList.add(new MyObject(3.5, 4.5, 6, "a"));
myArrayList.add(new MyObject(5.4, 2.6, 4, "b"));
}
For example, if I want to verify if there is an object which has the coordinates (3.5, 4.5), how should I proceed ?
Is there an easy way to do this ?
thanks for your help
The javadoc of List#contains(Object) states
Returns true if this list contains the specified element.
That's not what you're trying to do here. You're not specifying an element, you want to specify properties of an element. Don't use this method.
The long form solution is to iterate over the elements in the List and check them individually, returning true as soon as you find one, or false when you run out of elements.
public boolean findAny(ArrayList<MyObject> myArrayList, float targetX) {
for (MyObject element : myArrayList) {
if (element.x == targetX) { // whatever condition(s) you want to check
return true;
}
}
return false;
}
Since Java 8, there's a better way to do this using Stream#anyMatch(Predicate) which
Returns whether any elements of this stream match the provided predicate.
Where the given Predicate is simply a test for the properties you're looking for
return myArrayList.stream().anyMatch((e) -> e.x == targetX);
Regarding equality checks for floating point values, see the following:
What's wrong with using == to compare floats in Java?
Test for floating point equality. (FE_FLOATING_POINT_EQUALITY)
You can override equals function to define equal:
public class MyObject {
public float x;
public float y;
public int iD;
public String myType;
public MyObject (float x, float y, int iD, String myType)
{
this.myType = myType;
this.iD = iD;
this.x = x;
this.y = y;
}
#Override
public String toString() {
return ("[iD="+iD+" x="+x+" y="+y +" type="+myType+"]");
}
#Override
public boolean equals(Object o) {
if (o instanceof MyObject) {
MyObject myObject = (MyObject) o;
return myObject.iD == this.iD && myObject.myType.equals(this.myType);
}
return false;
}
}
Attention:
I must admit it's dangerous way to do this. override equals maybe will cause strange issues in program if you have used equals do some other compares. but in special case, maybe you can do that.
I am trying to assign value to a class variable via a method. However, after the execution comes out of the scope of the method, the variable is still initialized to the default value. How do we accomplish this in Java?
I want to initialize x to 5 by calling the method hello(). I don't want to initialize by using a constructor, or using this. Is it possible?
public class Test {
int x;
public void hello(){
hello(5,x);
}
private void hello(int i, int x2) {
x2 = i;
}
public static void main(String args[]){
Test test = new Test();
test.hello();
System.out.println(test.x);
}
}
When you do
hello(5,x);
and then
private void hello(int i, int x2) {
x2 = i;
}
it seems like you might be trying to pass the field itself as parameter to the hello method, and when doing x2 = i you meant x2 to refer to the field. This is not possible, since Java only supports pass-by-value. I.e. whenever you give a variable as argument to a method, the value it contains will be passed, not the variable itself.
(Thanks #Tom for pointing out this interpretation of the question in the comments.)
The class property x is only visible by using this.x in hello() because you have declared another variable called x in the method's arguments.
Either remove that argument:
private void hello(int i) {
x = 5;
}
Rename the argument:
private void hello(int i, int y) {
x = 5;
}
Or use this.x to set the class property:
private void hello(int i, int x) {
this.x = 5;
}
You can create two methods.
public void setX(int a)//sets the value of x
{
x=a;
}
public int getX()//return the value of x
{
return x;
}
call setX to set the value of x and getx to return the value x.
Essentially these are called getter and setter and we use them to access private members from outside the class.
I have been instructed to "Write a class, Triangle, with one instance variable that takes two string values, (filled or not filled)".
I'm new to Java, and still haven't come across a situation where you could have two potential values for one instance variable.
How would I do this?
main method was given:
public static void main(String[] args)
{
TwoDPolygon polygons[] = new TwoDPolygon[3];
polygons[0] = new Triangle("filled", 8.5, 12.0);
polygons[1] = new Triangle("not Filled", 6.5, 7.5);
polygons[2] = new Triangle(7.0);
for (int i=0; i<polygons.length; i++)
{
System.out.println("Object is " + polygons[i].getName());
System.out.println("Triangle " + polygons[i].getStatus());
System.out.println("Area is " + polygons[i].area());
}
}
Ok I have redesigned the code based on your updated question.
First of all, you need an abstract class called TwoDPolygon. This class is an abstract representation of all your polygons. It contains the constructors and the methods you need.
abstract class TwoDPolygon {
protected String filled;
protected double x;
protected double y;
protected TwoDPolygon(String filled, double x, double y){
this.filled=filled;
this.x=x;
this.y=y;
}
protected TwoDPolygon(double x, double y){
this.x=x;
this.y=y;
}
protected TwoDPolygon(double y){
this.y=y;
}
abstract String getName();
abstract String getStatus();
abstract Double area();
}
Then the next step is to create the Triangle class. You will have to extend the abstract TwoDPolygon. This is the code:
public class Triangle extends TwoDPolygon {
//the first constructor
public Triangle(String filled, double x, double y) {
super(filled, x, y);
}
//the second one
public Triangle(double x, double y){
super(x,y);
}
//the third one
public Triangle(double y){
super(y);
}
public String getName() {
return "Triangle";
}
public String getStatus() {
return filled;
}
public Double area() {
//Insert code here which calculates the area
return 0.0;
}
}
This is all. Every time when you instantiate a Triangle polygon it will chose the right constructor based on the parameters you supply. Now when you run your main you will have the following output:
Object is Triangle
Triangle filled
Area is 0.0
Object is Triangle
Triangle not Filled
Area is 0.0
Object is Triangle
Triangle null
Area is 0.0
Note: The area's code is not done. You will have to do that but I guess that shouldn't be a problem.
Also I have created three constructors as you said, but I don't know the parameters of the third one. I just guessed that it has only the x and y value.
I hope this is what you're looking for!! It shouldn't be that hard to adapt to your specific requirements, as I think it looks almost done.
It is most likely meant that it takes one argument with 2 valid values:
class Triangle {
Triangle(String val) {
if (!"filled".equals(val) || !"not filled".equals(val))
throw ...;
}
}
or enum type
public enum Type {
FILLED,
NOT)FILLED
}
I think what is meant is you have one boolean instance variable named isFilled.
then you could have something like this:
boolean isFilled;
public triangle(String filled, int x, int y) {
if (filled == "filled") {
isFilled = true;
} else if (filled == "notFilled") {
isFilled = false;
} else {
//handle exception or whatever
}
}
That way you can have one instance variable but still use a string in the constructor. I don't think this is a very practical thing to do but if that is what your assignment said then that is a good way to do it. I hope I helped!
I have been trying without any luck to make a list of all points in a model. When i execute this
HashList<Point> points=new HashList<Point>(16);
//add +y side
points.add(new Point(-5.0,5.0,-5.0));
points.add(new Point(-5.0,5.0,5.0));
points.add(new Point(5.0,5.0,5.0));
points.add(new Point(-5.0,5.0,-5.0));
points.add(new Point(5.0,5.0,5.0));
points.add(new Point(5.0,5.0,-5.0));
//add -x side
points.add(new Point(-5.0,5.0,-5.0));
points.add(new Point(-5.0,-5.0,-5.0));
points.add(new Point(-5.0,-5.0,5.0));
points.add(new Point(-5.0,5.0,-5.0));
points.add(new Point(-5.0,-5.0,5.0));
points.add(new Point(-5.0,5.0,5.0));
int length=points.length(); //equals 12, 6 expected
Point a=new Point(-5.0,5.0,-5.0);
Point b=new Point(-5.0,5.0,-5.0);
int aHashCode=a.hashCode(); //-737148544
int bHashCode=b.hashCode(); //-737148544
boolean equals=a.equals(b); //true
points containts 12 points which is the number I started with. I want all duplicates found which should result in only 6 points in table.
if (map.containsKey(e)) {
in HashList for some reason never gets executed. Any ideas?
HashList:
package dataTypes;
import java.util.ArrayList;
import java.util.HashMap;
public class HashList<E> {
private HashMap<E,Integer> map;
private ArrayList<E> data;
private int count=0;
public HashList() {
map=new HashMap<E,Integer>();
data=new ArrayList<E>();
}
public HashList(int size) {
map=new HashMap<E,Integer>(size);
data=new ArrayList<E>(size);
}
public int add(E e) { //returns key
if (map.containsKey(e)) {
return map.get(e);
} else {
map.put(e, count);
data.add(count,e);
return count++;
}
}
public int getKey(E e) {
return map.get(e);
}
public E get(int key) {
return data.get(key);
}
public int length() {
return count;
}
}
Point:
package geometry3D;
/**
* 3D point location or vector
*
* #author Matthew Cornelisse
* #version 2014-09-02-004500
*/
public class Point
{
// instance variables - replace the example below with your own
public double x;
public double y;
public double z;
/**
* Constructor for objects of class Point
*/
public Point()
{
// initialise instance variables
x = 0;
y = 0;
z = 0;
}
public Point(double x, double y, double z)
{
this.x=x;
this.y=y;
this.z=z;
}
public Point(Point a) {
x=a.x;
y=a.y;
z=a.z;
}
/**
* Normailizes the point to have distance from center of 1
*
*/
public void normalize()
{
// put your code here
double length=Math.sqrt(x*x+y*y+z*z);
x/=length;
y/=length;
z/=length;
}
//implements Shape
public void rotateX(double angle){
double newY=Math.cos(angle)*y-Math.sin(angle)*z;
double newZ=Math.sin(angle)*y+Math.cos(angle)*z;
y=newY;
z=newZ;
}
public void rotateY(double angle){
double newX=Math.cos(angle)*x-Math.sin(angle)*z;
double newZ=Math.sin(angle)*x+Math.cos(angle)*z;
x=newX;
z=newZ;
}
public void rotateZ(double angle){
double newX=Math.cos(angle)*x-Math.sin(angle)*y;
double newY=Math.sin(angle)*x+Math.cos(angle)*y;
x=newX;
y=newY;
}
public void rotate(Vector axis, double angle){
//source: http://inside.mines.edu/fs_home/gmurray/ArbitraryAxisRotation/
double oldX=x;
double oldY=y;
double oldZ=z;
double sinA=Math.sin(angle);
double cosA=Math.cos(angle);
Point offset=axis.offset();
Point vector=axis.vector();
double u=vector.x;
double v=vector.y;
double w=vector.z;
double a=offset.x;
double b=offset.y;
double c=offset.z;
x=(a*(v*v+w*w)-u*(b*v+c*w-u*oldX-v*oldY-w*oldZ))*(1-cosA)+oldX*cosA+(-c*v+b*w-w*oldY+v*oldZ)*sinA;
y=(b*(u*u+w*w)-v*(a*u+c*w-u*oldX-v*oldY-w*oldZ))*(1-cosA)+oldY*cosA+(c*u-a*w+w*oldX-u*oldZ)*sinA;
z=(c*(u*u+v*v)-w*(a*u+b*v-u*oldX-v*oldY-w*oldZ))*(1-cosA)+oldZ*cosA+(-b*u+a*v-v*oldX+u*oldY)*sinA;
}
public void move(double x, double y, double z){
this.x+=x;
this.y+=y;
this.z+=z;
}
public void move(Vector direction,double magnitude){
this.x+=(direction.vector().x*magnitude);
this.y+=(direction.vector().y*magnitude);
this.z+=(direction.vector().z*magnitude);
}
public boolean equals(Point compare) {
if (Math.abs(compare.x-x)>5*Math.ulp(compare.x)) return false;
if (Math.abs(compare.y-y)>5*Math.ulp(compare.y)) return false;
if (Math.abs(compare.z-z)>5*Math.ulp(compare.z)) return false;
return true;
}
public boolean equals(Point compare, double error) {
if (Math.abs(compare.x-x)>error) return false;
if (Math.abs(compare.y-y)>error) return false;
if (Math.abs(compare.z-z)>error) return false;
return true;
}
public int hashCode(){
Double a=(Double)x;
Double b=(Double)y;
Double c=(Double)z;
return a.hashCode()^Integer.rotateRight(b.hashCode(),12)^Integer.rotateRight(c.hashCode(),24);
}
public boolean equals(Object compare) {
try {
Point temp=(Point)compare;
if (temp.x!=x) return false;
if (temp.y!=y) return false;
if (temp.z!=z) return false;
return true;
} finally {
return false;
}
}
}
As noticed by rolfl, it is no use to try to use java equals method to compare Points with an acceptable error (see TL/DR section below if you are in doubt).
So, you have to do it the hard way. Do not even imagine to use map.containsKey(e), but create an explicit method in HashList. I would begin by that interface :
public interface DistEquality<E> {
boolean distEquals(E compare);
}
Then declare Point to implement it :
public class Point implements DistEquality<Point> {
...
public static double defaultError = 10E-3;
#Override
public boolean distEquals(Point compare) {
return equals(compare, defaultError);
}
}
And modify HashList that way
public class HashList<E extends DistEquality<E>> {
...
public int distValue(E e) {
for (Entry<E, Integer> entry: map.entrySet()) {
if (e.distEquals(entry.getKey())) {
return entry.getValue();
}
}
return -1;
}
public int add(E e) { //returns key
int pos = distValue(e);
if (pos != -1) {
return pos;
} else {
map.put(e, count);
data.add(count,e);
return count++;
}
}
...
}
I have not tested anything, but I think the general idea should be Ok.
TL/DR
Below solution is plain wrong - (thanks to rolfl to noticing)
The equals method in class Point requires exact equality of doubles. You should instead have a static double defaultError in Point class, initialized at an appropriate value and then do :
public boolean equals(Object compare) {
return ((compare instanceof Point) ? equals(compare, defaultError) : false);
}
But as noticed by rolfl, this is not enough, because javadoc for Object.hashCode() states If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
It would be very hard to imagine an intelligent hash compatible with the above equality method. Worse, once one point gets a hashCode value, any other point is at a finite number of defaultError and you can imagine a finished suite of Points that are all 2 per 2 equals and so hashCode should be a constant.
Worse, as equals is required to be reflexive, symetric and transitive, all Points should be equal.
It looks that the idea of using equal that way is really a bad idea :-(
The problem is your finally block in equals(Object). It's always returning false, even if you're returning true from the try block.
You're getting confused because of this:
boolean equals=a.equals(b); //true
... but that's not calling the same equals method - it's calling equals(Point).
Your equals(Object) method should be written as:
#Override public boolean equals(Object compare) {
if (compare == this) {
return true;
}
if (compare == null || compare.getClass() != getClass()) {
return false;
}
Point temp = (Point) compare; // Guaranteed to work now
return temp.x == x && temp.y == y && temp.z == z;
}
Note that:
As noted elsewhere, you can't come up with an equality/hash which handles tolerance... if you do any significant arithmetic with these points, you're unlikely to have exact equality any more
Your class has public fields, which is pretty much always a bad idea
Your class is mutable, which is a bad idea from the point of view of code using the hash code - collections are much easier to use correctly when the element type is immutable
If you make your class final, you can use instanceof instead of the getClass() check - and again, that would help prevent someone introducing a mutable subclass. (Equality relationships across an inheritance hierarchy are generally painful anyway.)
The HashList implementation is incorrect if you want it to be able to contain duplicates. On your add, if the map already has the key, you just return the value..., so your duplicates will never get inserted.
If you are getting duplicates, that means that your Equals/HashCode for Point is likely screwed up.
Right now, your HashList doesnt actually allow duplicates, so you might as well just get rid of it and use a HashSet from java collections. Also, get a decent java IDE like netbeans, eclipse, IntellIJ and have it generate the equals/hashcode for you on your point class.
I want to declare a List<int[]> or Map<int[],Boolean> but it's very difficult because arrays in Java doesn't implement the equals() method. If two arrays a and b are equal, a.equals(b) returns false.
Although java.util.Arrays.equals() compares arrays for equality, how do I get a List to use that method for comparison instead of the screwed-up equals()?
By the way, the int[] is a array [x,y,z] describing a coordinate. I want to put a bunch of these coordinates into a List or Map.
Why not declare your own class for a point? e.g.
class Point3D {
int x, y, z;
public boolean equals() {
// logic
}
}
and then declare List<Point3D>.
A general solution is to wrap the array in a method that does implement equals (and hashCode and perhaps compare, possibly toString and other methods that might make sense) as you wish:
public final class IntArrayWrapper {
private final IntArrayWrapper[] values;
public IntArrayWrapper(int... values) {
if (values == null) {
throw new NullPointerException();
}
this.values = values;
}
#Override public boolean equals(Object obj) {
if (!(obj instanceof IntArrayWrapper)) {
return false;
}
IntArrayWrapper other = (IntArrayWrapper)obj;
return java.util.Arrays.equals(this.values, other.values);
}
#Override public int hashCode() {
return java.util.Arrays.hashCode(values);
}
public int[] getValues() {
return values;
}
[...]
}
In this specific case, using arrays to contain certain fixed data values is poor design. Do it properly:
public final class Point {
private final int x;
private final int y;
private final int z;
public static Point of(int x, int y, int z) {
return new Point(x, y, z);
}
private Point(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
#Override public boolean equals(Object obj) {
if (!(obj instanceof Point)) {
return false;
}
Point other = (Point)obj;
return
this.x == other.x &&
this.y == other.y &&
this.z == other.z;
}
#Override public int hashCode() {
int hash;
hash = x;
hash = hash*41+y;
hash = hash*41+z;
return hash;
}
[...]
}
First of all, this isn't legal syntax. List can only take a single generic type.
Second, I would say that if you're worried about doing things at this low a level you aren't thinking abstractly enough. An array of arrays or a List of Lists is common enough. People who create matrix classes for linear algebra use them all the time. But you leverage objects and Java best when you hide those implementation details from clients of your class. Try it for your case and see if it helps.
You could always use the existing Point3d class instead of an array.
edit: The Apache Commons Math library also has some good options.