• 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:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Bear Bibeault
  • paul wheaton
Saloon Keepers:
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Mikalai Zaikin
  • Piet Souris
Bartenders:

using collection objects override methods

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi experts,

I have learned about collectable object's class override methods: equals, hashCode, toString and compareTo.

In the books I cannot see any call to equals method, where the actual looping and searching through collection is happening.

Are these methods intented to be used only by implementation classes (ArrayList, Collections, etc) "under hood" methods (like .binarySearch, .get, .sort, etc) ?

Or is there in real life some good and normal ways to use equals where the handling of collection happens?

Does changing a collection class to generic style have any impact on those methods (equals, hashCode etc)?

Thanks,
Kind regards MB
 
Marshal
Posts: 78444
374
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch

I find your post hard to understand. "Collectable object" isn't a term in common use. Do you mean an Object to be put into a collection (which you can do with just about every kind of object) or an instance of one of the Collection classes?
Those methods are of general use. You use toString() whenever you print an object, and equals() if you check for equality with another object. Not only when using collections classes.

If you don't override equals() and hashCode() correctly, you can put an object into a collection and never find it back. Yes, sort() uses compareTo() from Comparable<T>, or Comparator<T>#compare(), and search methods use equals().

And, as far as I know, generics makes no difference to the use of those methods at all.
 
M Berg
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am sorry, I mean just "an object to be put into collection".
I was just thinking if objects equals() works the same way and reliable in and outside that particalur collection class services.
Some code below...


package javaapplication1;

public class MyProduct implements Comparable<MyProduct> {

private int id;
private String name;

public MyProduct(int id, String name) {
this.id = id;
this.name = name;
}

@Override
public int hashCode() {
int hash = 7;
return hash + this.id;
}

@Override
public boolean equals(Object obj) {
if (!(obj instanceof MyProduct)) {
return false;
}
MyProduct other = (MyProduct) obj;
return this.id == other.id;
}

public int compareTo(MyProduct obj) {
return this.id - obj.id;
}

@Override
public String toString() {
return "Product id is :" + this.id;
}




}



package javaapplication1;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class MyCollections {

public static void main(String[] args) {

//Three spareparts in storage and one original model
List<MyProduct> myProdList = new ArrayList<MyProduct>();
MyProduct myp1 = new MyProduct(1, "sparepart a-prod");
MyProduct myp2 = new MyProduct(3, "sparepart c-prod");
MyProduct myp3 = new MyProduct(2, "sparepart b-prod");
myProdList.add(myp1);
myProdList.add(myp2);
myProdList.add(myp3);

MyProduct myp4 = new MyProduct(2, "original model b-prod");

//1. I quess I can see my objects overridden toString() with collections toString service ?
System.out.println(myProdList.toString());

//2. I quess this uses my objects overridden equals() here with collections sort service?
Collections.sort(myProdList);

//3. I quess I am using my objects overridden equals() here with collections contains service?
boolean foundmatch = myProdList.contains(myp4);
if (foundmatch) {
System.out.println("Yahoo myp4 we found a matching sparepart with clever underhood method");
}

//4.
//is this completely ok and as legal... so I can call equals() detached from collection?
Iterator<MyProduct> iter = myProdList.iterator();
while (iter.hasNext()) {
MyProduct product = iter.next();
if (product.equals(myp4)) {
System.out.println("Yahoo we found a match but with more work?");
}
}

}
}
 
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
equals / compareTo, hashcode

these are the building blocks for Objects comparison /search and hashing
All three have their default implementation ....

To make effective /customize use of these comparison /search and hashing ; you should override respective methods...

override hashCode would help you achieving customized hashing of Objects --
override Equals -- comparing references /objects
compareTo --- sorting Objects ---

These methods are supposed to meet certain requirements (contracts) to see them work as expected....
To understand more on these methods: http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf

find more on for example: https://coderanch.com/t/458535/java/java/equals-hashCode-methods#2045659

I found you questions a bit interesting (and i got confused too )

M Berg wrote:
Are these methods intented to be used only by implementation classes (ArrayList, Collections, etc) "under hood" methods (like .binarySearch, .get, .sort, etc) ?


No -

M Berg wrote:
Or is there in real life some good and normal ways to use equals where the handling of collection happens?


Yes ..... you have to (don't Overeride it if you don't want bug free code )

M Berg wrote:
Does changing a collection class to generic style have any impact on those methods (equals, hashCode etc)?


Generics usage in Collection helps you TRACK runtime ClassCastException on Compile time (but doesn't guaranty; I 've seen good pragrammer using Generic but still beating Java ) nothing much....
This adds a more Type Casting to you code nothing else.. some plp think it enhances performance but that's a MYTH...no performance gain is achieved
 
Campbell Ritchie
Marshal
Posts: 78444
374
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

K Abhijit wrote:Yes ..... you have to (don't Overeride it if you don't want bug free code )

What does that mean? It's hardly clear with all those "not"s.

Generics usage in Collection helps you TRACK runtime ClassCastException on Compile time (but doesn't guaranty; I 've seen good pragrammer using Generic but still beating Java ) nothing much....
This adds a more Type Casting to you code nothing else.. some plp think it enhances performance but that's a MYTH...no performance gain is achieved

And what does that mean? Generics will guarantee to avoid ClassCastExceptions by creating compiler errors instead, if used throughout without suppressing or ignoring any warnings.

And please don't say "plp" or similar.
 
Campbell Ritchie
Marshal
Posts: 78444
374
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

M Berg wrote:I mean just "an object to be put into collection",

Thank you.

M Berg wrote:I was thinking if equals() works the same way and reliable in and outside that particalur collection class services. . . .

Your equals() looks correct, provided you never extend from that class. So does your hashCode() look correct, similarly.

As I said, there may be all sorts of situations where you need to check that two object references are "equal" to each other. You will find three nice links about equals() in this post by Garrett Rowe.
 
K Abhijit
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Campbell:
the argument I made was in general. not with respect to Collection...
Look at this code:



this gives run time error: Class cast @ 23
this uses Generics(but they are not properly handled)
Hence I said it doesn't guaranty Type Safety unless correctly coded...
AS you rightly said, it does flag warning , but generally Warning do get Ignored by Programmers (only Errors are taken into consideration )

Code copied from
http://stackoverflow.com/questions/372250/java-generics-arrays-and-the-classcastexception

 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can't cast an object array to an T array. You also can't create a generic array.
Search for generic array creation and you'll find some "solutions".

// Well you can but it isn't really a proper solution.
 
K Abhijit
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Oet:

I've already mentioned that it is improper use of Generics.
The example given was just to defend my Argument that Generics DOESN'T guaranty NO ClassCastException (and I still stand by it ) nothing more than that...

When you say Guaranty that means Programmer would not able to run Code that would break it runtime with that exception...
if it allows you to run such buggy code that means it DOESN'T guaranty...I rest my argument here ... hope no more Questions would be there..

You can't cast an object array to an T array. You also can't create a generic array.


you point is correct and accepted in semantic way but Syntactical base; I'm afraid I can't take it.
For me, in any prog lang I can do anything unless it forces me NOT TO Do so. if it doesn't flag ERROR, I'm fine with it.
(I know the outcome would be bad -- runtime error )

hope i'm a bit clearer....

 
author and iconoclast
Posts: 24204
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

K Abhijit wrote:if it doesn't flag ERROR, I'm fine with it.



One hopes your project leads are somewhat more conventional in their thinking.
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In that way generics provide almost the same guaranties as arrays:
Compiles just fine.
 
K Abhijit
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@ Oet :
Completely agree
 
K Abhijit
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ernest Friedman-Hill wrote:One hopes your project leads are somewhat more conventional in their thinking.



well, i'm personally think like that, it's just a perception whether to consider it Conventional or Liberal
Anyway, i agree that the approach definitely doesn't fall under Best Practices

 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
Low Tech Laboratory
https://www.kickstarter.com/projects/paulwheaton/low-tech-0
reply
    Bookmark Topic Watch Topic
  • New Topic