• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Devaka Cooray
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
Bartenders:

Returning An Array Element, Not the Address Of The Array Element

 
Ranch Hand
Posts: 130
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello folks, I have written a method that searches through an array and prints out a specific element.
But my code only prints out the address of the element. I want to print out the String element of the array.

Here is my search method,


Here is also the code that tries to print out the element.

Thanks you.
 
Marshal
Posts: 81613
593
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You cannot print the address of anything in Java®. You don't have access to addresses. I suggest you start by looking here. I think your problem is that you haven't overridden all the methods you ought to.
Also, don't return null if you can avoid it. Find something else to return if at all possible.
 
Kelvin Okornoe
Ranch Hand
Posts: 130
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I looked where you asked me to look, thanks for that Sir, You mean I have to override the toString() method.
 
Saloon Keeper
Posts: 29001
214
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Kelvin Okornoe wrote:I looked where you asked me to look, thanks for that Sir, You mean I have to override the toString() method.



You are correct.

I disagree with Campbell, here. Searches belong to a class of functions that have a problem with return values in that the search normally should either return a match value or a "not found" indicator. Two different and mutually-exclusive types of data.

Some people return an "obviously false" value such as "-9999" or "<NOTFOUND>" or in your example, perhaps an empty array, but I don't like that approach because it's too easy to mistake the "notfound" value for a valid value. And sometimes the "invalid" value becomes valid after the program has been modified. On the other hand, "null" is very obviously and forever a non-valid value, and thus makes a better choice.

There are basically 4 ways to deal with a search that can return heterogeneous responses like this.

1. Return an "invalid" value

2. Return a truly invalid value (in Java, that would be null) - Preferred solution A

3. Return a tuple, where one result is the search match value and the other is a boolean found/not found indicator. This works much better in languages like Python and Perl than it does in Java

4. Return only valid values and throw an Exception when a match is not found Preferred solution B

Generally, I like Exceptions, but my experience with searches is that often it's simpler and cleaner (and less overhead) to return null instead. Your preferences may vary.
 
Kelvin Okornoe
Ranch Hand
Posts: 130
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you @Tim Holloway, that was nice information and wisdom.
 
Kelvin Okornoe
Ranch Hand
Posts: 130
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have added the overridden toString method to my code. But I am having the same result. I hava decided to paste the whole code here for help.

Code for Contact Class.


Code for ContactsManager Class.


Code for Class that contains the main method.

Thanks guys for your time and knowledge in advance
 
Bartender
Posts: 15743
368
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Operations that can possibly return "no results" should, since Java 8, return an Optional, if they wouldn't otherwise be of a collection type. In this case:
 
Marshal
Posts: 6208
501
IntelliJ IDE Python TypeScript Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Do you think you have the toString() method in the right class?
 
Kelvin Okornoe
Ranch Hand
Posts: 130
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tim Cooke wrote:Do you think you have the toString() method in the right class?



Yes Please
 
Tim Cooke
Marshal
Posts: 6208
501
IntelliJ IDE Python TypeScript Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't understand your last post... but anyway... The toString() method allows you to define what the String representation of your class looks like so that when a method such as System.out.println is given an instance of that class it can call the toString() method and print the result of that call to the console.

Now, look very carefully to see what object it is that you're printing to the terminal.
 
Kelvin Okornoe
Ranch Hand
Posts: 130
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tim Cooke wrote:I don't understand your last post... but anyway... The toString() method allows you to define what the String representation of your class looks like so that when a method such as System.out.println is given an instance of that class it can call the toString() method and print the result of that call to the console.

Now, look very carefully to see what object it is that you're printing to the terminal.



The Object that gets printed is an Object of the Contact Class.
 
Tim Cooke
Marshal
Posts: 6208
501
IntelliJ IDE Python TypeScript Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Right, so where do you think you might need to override the toString() method?
 
Kelvin Okornoe
Ranch Hand
Posts: 130
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tim Cooke wrote:Right, so where do you think you might need to override the toString() method?



The Contact Class.
 
Kelvin Okornoe
Ranch Hand
Posts: 130
2
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Kelvin Okornoe wrote:

Tim Cooke wrote:Right, so where do you think you might need to override the toString() method?



The Contact Class.



Thank you, Tim Cooke, it worked.
I appreciate you so!! much.
Thank you again
 
Tim Holloway
Saloon Keeper
Posts: 29001
214
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:Operations that can possibly return "no results" should, since Java 8, return an Optional, if they wouldn't otherwise be of a collection type. In this case:



Let me add that as option #5 on my list. I tend to forget about Optional because I'm not working as actively with Java as I was. Plus this is the kind of thing that you'd do on new code more than on maintenance code, where you'd have to refactor.

Optional is a kludge to deal with the fact that Java is not 100% object-oriented. If Java were fully object-oriented, then there would be no primitives. No ints, no chars, and no null as we know it and there would probably be a "null" object that looks a lot like Optional. Optional is basically an object-oriented version of null and is designed so that if you code an expression that returns an object you'll get something that can be operated on without fear of throwing a NullPointerException.

Note that Optional is a Template (Generic) class, and so requires an explicit reference class. Were it not so, then attempting to invoke methods implemented by that class would itself throw an exception.

Because it's a template class, it cannot be used for non-object types. Meaning primitives and arrays. Of course, if a method returns a primitive number, byte or character type, neither Optional nor null apply and you're pretty much limited to throwing an exception or returning an "obviously invalid" value. Arrays are neither primitives nor classes, so you can return null for that particular case.
 
Stephan van Hulst
Bartender
Posts: 15743
368
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In those cases I would, for example, return Optional<Integer> and Optional<Foo[]>.
 
Campbell Ritchie
Marshal
Posts: 81613
593
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tim Holloway wrote:. . . I disagree with Campbell, here. Searches . . . have a problem with return values in that the search normally should either return a match value or a "not found" indicator. . . .

Point taken. There isn't, as you said, an ideal return type. But what is going to happen if you return null and try to use it? If you do more than simply print it out, you are risking an Exception. That is why I said to avoid it if you can. You have shown that it may be unavoidable given the constraints. Most searches return the index of the first element found matching the search criterion, with −1 as a default “not found” indicator, which I think is a historic relic of the conventions of C, or maybe even earlier. But I presume the constraint “Not the Address” means you can't return the index either. I think throwing an exception from the search would be overkill; besides, “not found” is a “normal” occurrence and “normal” occurrences don't usually merit exceptions.
Isn't null a kludge, invented by Sir Tony Hoare about 1960, requiring another kludge (Optional<T>) to try and sort it out ? Hoare says null was the biggest mistake of his whole career.

I think you have shown that null might not be ideal, but all other potential approaches are worse, so null it is. Unless this is new code, and we can use your suggestion of an Optional. You cannot simply use the get() method of an Optional without checking for the existence of a value first. You could use something like myOptional.orElse(new Contact("???", "???", "???")) That simply moves the problem of an invalid object somewhere else, doesn't it?

I am not convinced that i should be a field of the contact manager class; I would prefer to see it as a local variable. I would also prefer to see all fields given private access, so they can only be manipulated via methods. That also would allow the array to be replaced by a List<Contact> without breaking any other code
 
Rancher
Posts: 1044
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:But what is going to happen if you return null and try to use it? If you do more than simply print it out, you are risking an Exception.



Well, if you return something only seemingly useful, then you risk using that non-sensical value and this might be even worse than having an indication that something went wrong via the NPException.

If you search for something then in some way or other you have to cope with the case when it is not found: let it be through examinig for null, for a nonsensical sentintel value, a return code, whatnot.
 
Stephan van Hulst
Bartender
Posts: 15743
368
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The discussion here is, which is best?

For new code, Optional is the best (yes, even in the case of arrays). It was explicitly created for the purpose of dealing with situations where a return value was not found. It forces the user of a method to think about this possibility and decide how they want to deal with that at compilation time. None of the other options do that. I was mistaken earlier about Optional<Integer>, for primitives there are types such as OptionalInt.

For pre-Java 8 code dealing with simple cases, I think returning null is the best option. While it doesn't force the programmer to think about cases where the result isn't found, at least it will crash the application if someone tries to do something silly with it. The .NET library throws an exception when you get an element out of a dictionary using an indexer if the index doesn't exist, and as a result nobody uses the indexer.

For complexer cases, I think it's best to return a custom object. A good counter-example is the Collections.binarySearch() method. If it can't find the index of the element you're looking for, it returns the index where the element would be located if the list contained it. To differentiate the two cases, when an element is not found, the result will be negative. But it's not as simple as negating the insertion point, because that would mean that you couldn't differentiate between finding an element at index 0, and not finding an element at -0. So when an element isn't found, the index it would have been located is negated, and then 1 is subtracted from it. For an element that was not found, but would be located at index 3, binarySearch() returns -4. This is not easy to work with at all. I have to look up the documentation every time to figure out how it works. Instead, it should have returned an object that looks roughly like this:
 
The first person to drink cow's milk. That started off as a dare from this tiny ad:
Paul Wheaton's 16th Kickstarter: Gardening playing cards for gardeners and homesteaders
https://coderanch.com/t/889615/Paul-Wheaton-Kickstarter-Gardening-playing
reply
    Bookmark Topic Watch Topic
  • New Topic