comparing object calling the method - java

i know this is very trivial, but for some reason i'm having a little trouble. i'm trying to write a method that has a book object from an array list calling the method that compares it to another book in the same list. I think i got the gist of it but i'm just not understanding how to compare them. i think it's supposed to look something like this.
public Boolean isShorter(Book otherBook)
{
if(otherBook.getLength() < ???????.getLength() )
return true;
else
return false;
}

use "this" keyword to refer to the current object (the caller of the method).
like this:
otherBook.getLength() < this.getLength()

Related

Java Method Confusion

In Java, when for example you say string1.compareTo(string2), how is the compareTo method accessing the string1. I see the method takes in the second string but how does it compare it to the first if it is not getting passed along?
compareTo() is a member function of Class String, this means that for invoking this function you need an Object of Type String. So when you say string1.compareTo(string2) , this means that you are invoking compareTo() function on the String object 'string1' and passing 'string2' as the argument.
I think this little 'illustration' could help you
Class String {
public int CompareTo(String string2)
{
if (this==string2) return 1; //The == is completely wrong here but it gives you an idea on how it works
else return 0;
}
}
When you call string1.CompareTo(string2); in the method, this will reference the object itself, so here it references string1

Java - pass a pointer to an object to a function

What I want to achieve is something like this:
MyClass object = null;
doStuff(&object);
// `object` can now be non-null
What I'm currently doing is this, but I think there must be a better way to achieve this behavior in Java:
MyClassPointer pointer = new MyClassPointer(null);
// pointer.object is null
doStuff(pointer);
// pointer.object can now be non-null
If you really want doStuff to return two values: There may well be a better way to design this. Nevertheless, if you've decided that having doStuff return two values is really the best design, it can be done with a simple helper class:
static class MyClassAndBoolean {
public MyClass obj;
public boolean b;
public MyClassAndBoolean(MyClass obj, boolean b) { this.obj = obj; this.b = b; }
}
and then change doStuff's return type to MyClassAndBoolean. This is one of the very few cases where I think public fields in a class are OK. Since you're defining a simple class just to use as a function result, rather than representing a coherent concept, the usual concerns about defining accessors instead of exposing fields, etc., don't really apply. (P.S. I just guessed at boolean for the other type, but it can be anything, of course.)
Another workaround:
MyClass[] obj = new MyClass[1];
result = doStuff(obj);
Change doStuff's parameter type to MyClass[], and have it stuff the new object into parameter[0]. I do see this idiom used in some of the Java and Android library methods.
Why not simply:
MyClass object = doStuff();
which is much more intuitive IMHO. Otherwise you have to pass a reference (not pointer!) to a container object to your method, as you've identified. That's not a common pattern in the Java world.
As far as I know java language it is the only way to do that.
But you can simply implement method into your class. And in your method also there is possibility to return your object.
public MyObject myFunction(){
//do stufff...
return new MyObject();
}
MybObject object = myFucntion();
Or you can do it in your way. Also using Reflection you can invoke your method.
Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);
No, there is no better way since in Java you don't have pointers the way you have them in C++.
In Java references (much like pointers in C++) can't be directly accessed and are always passed by value. Thus you can't change the value of a reference within a method.
Use the Visitor pattern, your MyClass being what have to be 'visited' by dostuff

Cant get public boolean removeBorrower(String libraryNumber) to work

The code needs to be able to reference two library numbers together, and if they are equal, remove the borrower from the array.
It won't let me run a method from another class because it's a static context. I don't know how else to solve this.
Here is what I have so far:
public boolean removeBorrower(String libraryNumber)
{
if(libraryNumber == null)
return false;
else if(Borrower.getLibraryNumber().equals(libraryNumber)))
borrowers.remove(Borrower);
return true;
}
You need to pass a reference to the other Borrower you want to compare against:
public boolean removeBorrower(String libraryNumber, Borrower otherBorrower)
{
if(libraryNumber == null)
return false;
else if(otherBorrower.getLibraryNumber().equals(libraryNumber)))
borrowers.remove(otherBorrower);
return true;
}
Before, you were trying the get the library number for the generic Borrower class, which doesn't make conceptual sense. With this code, you have a specific person to check the library number of.
You need to get an instance of the class containing removeBorrower method.
I don't think that you can't run the method from another class (unless the method is contained in a package-private class and the client class is not part of the same package).
Maybe you wanted to say that you're not allowed to run this method without having a reference to an existing instance of the class containing removeBorrwer method.

Do I use list.remove correctly?

Assume that I know that the list SomeList contains thatObj. Does the following code remove reference to thatObj from SomeList or not?
SomeClass el = (SomeClass) thatObj.clone();
SomeList.remove(el);
Can't find through the reference if this method compares objects somehow. Intuition suggests that it should use Object.equals which returns true if references point to the same object, hence this code will not work.
If not then an additional question: how to remove from list if don't have the reference but know all the members of the object in question?
Can't find through the reference if this method compares objects somehow. Intuition suggests that it should use Object.equals which returns true if references point to the same object, hence this code will not work.
Yes, you are right.
If not then an additional question: how to remove from list if don't have the reference but know all the members of the object in question?
Two possibilities:
override the equals method in your class, create a new instance with all known members and call remove passing the newly created instance as a parameter
iterate through all the objects inside the list and remove the one that has the members equal to the values you have
remove method internally uses the equals method to check for the object in the list. If equal returns true then it will be removed. Overriding the equals method will allow to remove the objects properly. For your reference here is the code of ArrayList remove method:
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
Override the equals method on the class - here is the javadoc. Also look at Overriding the java equals() method quirk and Overriding equals and hashCode in Java.
Search the list to find the member by returning the index, then get the object and remove it. You can also remove it by the index. The code
SomeList.indexOf()
could help you to get the index of the object that override equals() and hashCode().

What should I use as the return statement?

I am creating a method called swapElements(). It takes an array of integers, and two integer indexes. The method should swap the values of the array elements with the specified indexes.
public class{
int swapElements(int[] number, int value1, int value2){
int temp = number[value1];
number[value1] = number[value2];
number[value2] = temp;
}
}
As you have presented it, this method does not need to return anything, and should probably be declared void. However, if there is a specific contract it needs to fulfill then you should return whatever the interface definition says it should return.
There are four things wrong with your code.
The thing you're asking about: use return number;, because you want to return the array with swapped elements.
Make the method return an int[] (like int[] swapElements), not an int.
Your class has no name. You need to add a name, like public class IntArraySwapper { ....
Your method should be static. Without using that keyword, you must call it on an instance, like new IntArraySwapper().swapElements(...). Since this method has nothing to do with class instances, simply make it static (static int[] swapElements) so that you can call it like IntArraySwapper.swapElements(...).
Note that the method will also modify the original array, so techinically you don't need to return anything. If you want, you could just make it a void method and use the old array.
you can just make it return void.
or maybe a boolean to indicate that the sawp happened, with no errors.
like index out of range error.
In such cases the return type is not strictly required. So, you should return void. But if you indeed want to return something, consider returning boolean to specify if the swap happened or not. More precisely you can include the swap code into try catch block which returns True if the swap happened without any error and False otherwise.

Categories