Results 1 to 5 of 5
Thread: Set of user defined class
- 07-05-2012, 06:40 AM #1
Member
- Join Date
- Jul 2012
- Posts
- 3
- Rep Power
- 0
Set of user defined class
I want to define a set of user defined class. e.g. let's say I've class defined as
Java Code:public class point { int x,y; } Set<point> Points; Points = new HashSet<point>();
Java Code:P = new point(x1,y1); Points.add(P);
- 07-05-2012, 07:49 AM #2
Senior Member
- Join Date
- Jun 2007
- Location
- Bali, Indonesia
- Posts
- 762
- Rep Power
- 14
Re: Set of user defined class
To make it work correctly you have to implement both equals() and hashCode() methods in your Point class. This will make sure that your Set store Points with unique x and y value.
Last edited by wsaryada; 07-05-2012 at 08:38 AM.
Website: Learn Java by Examples
- 07-05-2012, 08:14 AM #3
Member
- Join Date
- Jul 2012
- Posts
- 3
- Rep Power
- 0
- 07-05-2012, 08:42 AM #4
Senior Member
- Join Date
- Jun 2007
- Location
- Bali, Indonesia
- Posts
- 762
- Rep Power
- 14
Re: Set of user defined class
When we are working with the collection classes in Java we must provide a correct and consistent hash value for each equals object. If we don't provide a the hash it will be generated by the collection framework which result in a different hash code for an object that we considered to be equals. So to make it work as expected we must provide the hash code that is generated from the same properties that we used in the equals method.
Website: Learn Java by Examples
- 07-05-2012, 10:58 AM #5
Moderator
- Join Date
- Apr 2009
- Posts
- 13,541
- Rep Power
- 27
Re: Set of user defined class
Not any collection.
Just the ones that use Hashes (ie HashSet, HashMap).
Similarly with equals and Sets.
Trees require either implementing Comparable or a Comparator.
It's all documented in the various APIs.
Can I just suggest to the OP that they use naming standards?
The class name and object names in the above code are back to front.
Should be 'Point' for the class and 'points' for the variable.Please do not ask for code as refusal often offends.
** This space for rent **
Similar Threads
-
Problem with user defined class
By moosethmucha in forum New To JavaReplies: 8Last Post: 04-17-2012, 06:58 PM -
how to write user defined class as Immutable?
By srinivasmallabathula in forum New To JavaReplies: 3Last Post: 07-05-2011, 12:50 AM -
Problem with user defined class in ArrayList
By anders73 in forum New To JavaReplies: 4Last Post: 04-26-2011, 04:59 PM -
User Defined Method
By overcranked in forum New To JavaReplies: 6Last Post: 04-09-2010, 02:02 AM -
JSP with user-defined java classes
By adammyth in forum JavaServer Pages (JSP) and JSTLReplies: 2Last Post: 03-05-2010, 07:13 PM
Bookmarks