I'm implementing my own java treeset. I think the underlying data structure is a BST and each node in the tree contains Object type data field. However, I stuck at how to compare two Object type data using natural ordering comparator. Is there a compareTo function that compares two objects and return the value of their natural ordering? I'm also thinking using hashcode as index key for each node and do comparison based on that. But it seems that distinct object might have same hashcode. Any advice is appreciated.
instead of BST consider RBT (Red black tree). look at here for more reference.
Now your MyTreeSet can take two kind of objects.
1. Object of java given wrapper class like String, Integer, Long etc Or
2. Object of your own written custom classes.
If your data structure needs to support case 1 one then order can be done easily based on compareTo method which is implemented by all java given wrapper class. You only need to call compareTo method to know which object is greater, equal or lesser than others based on it's return value 0, negative and positive value.
For case 2, that means your MyTreeSet needs to take object of custom classes also then you should implement Comparable interface to your custom classes and write your comparison algorithm there. For example if you want MyTreeSet should take Employee class object then implement Comparable method in Employee class and write implementation of compareTo method based on how emp1 will be compared to emp2. You may want to sort them based on their employee ids.
Hope it helps you.
Related
Suppose we have two employee instances having some common attributes like id,name,address (All values are same ).
I want unique objects list without implementing Set.
Please don’t explain the logic with Primitive data type ,I want the uniqueness with Object type.
Simple: you create a "collection" class that calls uses the equals() method of "incoming" objects to compare them against already stored objects.
If that method gives all false - no duplicate, you add to the collection. If true - not unique. No adding.
In other words - you re-invent the wheel and create something that resembles a Java set. Of course, with all the implicit drawbacks - such as repeating implementation bugs that were fixed in the Java set implementations 15 to 20 years ago.
If you don't want to use a Set, use a List. All you need to know to implement uniqueness checking logic is whatequals(Object other) method does:
Indicates whether some other object is "equal to" this one
Now you can test an incoming object against all objects currently on your list, and add it if a match is not found.
Obviously, performance of this method of maintaining a unique collection of objects is grossly inferior to both hash-based and ordering-based sets.
If you cannot use a Set for holding unique instances of your Employee class, you can use a List. This requires you to do two things:
Override equals() (and hashCode()) in Employee to contain the equality logic. This you would need even if you used a Set.
Each time you add items to the list, use List.contains() for checking whether an equal object is already in the list. The method will internally use your Employee.equals() implementation. Add an item only if it's not already in the list. Note that this method is quite inefficient as it needs to iterate through the whole list in worst case (when an item is not already in the list).
I have a Matrix class that has the following attributes: number of Lines, number of columns and a matrix of Objects.
I have to find the minimum element of the matrix of Objects. How could I do that if I don't know what my Objects will be in JAVA?
You can use either the comparable or comparator functions to, effectively sort arrays of objects by a specific value. You will, depending override the compare to value and select an instance field to make comparisons with.
Use reflection to find out of the objects implement comparable and are all the same type or same base type, and that base type implements Comparable.
if not go thru all the fields, for every field that is a string or a number, compare with corresponding... if its an object go in to that and find strings and numbers. Can make a generic comparator. If a field is a collection then poke in to the type and process similarly. Not an easy task but doable. You could also choose not to go more than x level deep by keeping a current level int that you pass around your stack (if you get in to properties that are objects)
I have a arraylist and it contains a 100 employee object and each object contains "Name" and "Salary". We need to find the Max salaried employeee from the Object .Please let me know what is the way .
I thought of implementing compareTo and equals Method is it right , and also using Collections.sort Is it the right way or is there any other way
If the language is Java, then either implement the Comparable interface (just compareTo--no need for equals) for the objects in the array list and call Collections.sort(arraylist), or else write a Comparator and call Collections.sort(arraylist, comparator). The latter is more flexible, as it doesn't require your objects to always be sorted by salary.
You need not do the sorting yourself. Your case is perfect for priority queues. Write a comparator as #Ted suggested and add the data to PriorityQueue - it'll give you the min or max based on the data you want the min/max of - salary in your case. Details in this post:
How do I use a PriorityQueue?
Is it possible to search an array of objects in Java by a private attribute with the Array.binarySearch method? I was thinking there must be something similar to the sorting technique, where you create a class that implements Comparator and pass this in to Array.sort, but I can't seem to find anything (maybe there is something where instead of the compareTo method you just return the attribute used in the search)??
To be clear I have an array of anonymous Station objects, and this is passed to another class where I want to search the array for the name of the stations, which can be returned via a getName().
Any help would be much appreciated!
Yes - in fact it uses Comparator, which you specified in your answer!
If you have a look over the implementations of the binarySearch method in the API, you come across binarySearch(T[] a, T key, Comparator c) which:
Searches the specified array for the specified object using the binary search algorithm.
You can implement the Comparator however you like, and so can use it to compare the private attributes alluded to in your question.
Edit responding to comment: The T is a generic parameter, meaning it can be anything, so long as it's the same in every position it appears. In this case, it means that the first parameter must be an array of the second parameter's type. Or in other words, if you're sorting an array of Ts (Stations in your case) then you need to pass in an instance of that class (Station here) to act as the object to compare against. This key argument will always be passed in as one of the arguments to the comparator's compare method.
So I suspect in your case you were passing in a String representing the station name; you should instead pass in an instance of Station which has the appropriate name.
Yes, there's an overload that takes a comparator. Remember that you can only use binarySearch if the array is already sorted.
If the array of stations is not already sorted by the station names, it makes no sense sorting and searching for every query. It is faster to do a linear search in this case. However, if you can sort the array and then perform multiple binary searches, it is worthwhile. Implement a comparator such as the following, and use it for both sorting (Arrays.sort(..)) and searching (Arrays.binarySearch(..)):
private class StationNameComparator implements Comparator<Station> {
public int compare(Station s1, Station s2) {
return s1.getName().compareTo(s2.getName());
}
}
Note that I assume that the names are non-null and unique.
Thanks, eventually got it working using
Arrays.binarySearch(allStations,new Station("nameofstationhere"),new StationCompare())
which is probably a bad way as I'm creating a new Station object for comparison... but it works and not sure how to do it using just the string...
in which situations we have to implement the Comparable interface?
When you want to be able to compare 2 objects and get a result of equal, less than, or greater than.
Implementing Comparable gives your objects a compareTo method. If you add them to a sorted list then they will automatically be sorted based on what your compareTo method returns.
It's pretty basic. I don't know what else there is to add.
When your class implement the Comparable interface, you have to implement the compareTo() method in a way that you can clearly tell where an instance of your class would go in an ordered list of such instances.
Implementing efficient sorting algorithms and ordered collections isn't trivial. Therefore you would do this when you want objects of a class to have natural ordering, so you can use the proven sorting and order-dependent algorithms and classes provided by Java instead of implementing your own, like having the contents of a TreeSet remain ordered after insertions/deletions, or using Collections.sort().