Compareto Implementation Policy

Source: Internet
Author: User
Tags addall

1. compareto is used for treeset, while treeset personally thinks it is best to read the DB result set. In the future, subset can be obtained based on compareto sorting results. When writing a database, you can use hashset instead of treeset, because the sorting and subset of the structure before writing do not need to be considered.

2. How to Implement compareto: Determine the probability of conflicting fields to be compared in sequence.
Assume that the table structure is memberid, locationid, type, and memberid. The locatonid is the primary key combination. Such a memberid can correspond to multiple locationid records.
If you read all the records of a member from the database and put them in the treeset, and sort the records by type in the future, type must first appear in compareto, and only type, other records of the same type may not be added to the treeset. Therefore, you need to pull a field similar to identify, which is of course the locationid.
In this case, the fields to be compared are type and locationid. Based on the possibility of conflict, of course, the first type and then the locationid.

Example: The implementation policy of putting the memberlocationelement object into the compareto in the treeset: first judge the most likely same type value, and then judge the locationid that is most likely to conflict with each other. Treeset is mainly used to read the result set from the database. When writing data, you must ensure that the locationid is different. You can use hashset to write data. Therefore, treeset personally thinks the best way is to use it during reading. Instead of performing the add operation.

    public static class MemberLocationElementComparator implements Comparator<MemberLocationElement>,Serializable{        private static final long serialVersionUID = 1L;        @Override        public int compare(MemberLocationElement o1, MemberLocationElement o2)        {            if (o1 == null || o2 == null)                return -1;            if (o1.getType().getVal() == o2.getType().getVal())            {                return o1.getLocationid() - o2.getLocationid();            }            return o1.getType().getVal() - o2.getType().getVal();        }    }

 

For example, if the person record is read from the db to the treeset, the person contains the FN and LN attributes, indicating first_name and last_name respectively. Assume that FN + ln constructs a composite primary key. If you want to read all user records to the treeset
In this case, the compareto field should be FN and LN. Note that ln is not an identify field. However, since FN + ln is identify, the probability of conflict arises, FN conflicts are more likely, so we should first compare them.
For example, if you join Li Xiang or Li Chen, you cannot join Li Chen because of first_name = Li. If FN is equal, you can compare ln.
For different FN types, you can add them to treeset. For the same FN type, you need to compare last_name to prevent them from being added.

Photoinfo contains values of blessed and uploaddate. The value of Blessed ranges from 0 ~ 7. If a sorting result of 2> 1> 6 is implemented, sort by uploaddate in the same case (the last one is displayed first)

The comparator is implemented as follows:

Public static class testcomparator implements comparator <photoinfo>, serializable {Private Static final long serialversionuid = 1l; public static final map <integer, integer> blessedindmap = new hashmap <integer, integer> (); static {blessedindmap. put (userimage. s_blessed_geo_parent, 3); blessedindmap. put (userimage. s_blessed_geo_only, 2); blessedindmap. put (userimage. s_blessed_property_only, 1) ;}@ overr IDE public int compare (photoinfo O1, photoinfo O2) {If (O1 = NULL | O2 = NULL) {return-1 ;} int bind1 = getindexbyblessed (o1.getblessed (); int bind2 = getindexbyblessed (o2.getblessed (); If (bind1 = bind2) {// recently first show, because the default values are ascending, therefore, the negative value is used. Return-(o1.getuploadeddate (). compareto (o2.getuploadeddate ();} // blessed show order, 6, other, because the default values are ascending, so take a negative value. Return-(bind1-bind2);} public int getindexbyblessed (INT blessed) {return blessedindmap. Get (blessed) = NULL? 0: blessedindmap. Get (blessed );}}

For list, use the following tool: collections. Sort (photoinfolist, new testcomparator ());

 

3. It is particularly emphasized that map can only compare values through comparator. If you want to sort keys or make an ordered map, you can only use linkedhashmap, which supports sorting by the added order.

 

4. Divide and use the treeset interface:
For remove, removeall operations depend on the equal method defined by element.

Operations such as ADD, addall, headset, tailset, and subset depend on the compareto method.

Tailset + headset is used to obtain the result set of a certain range. The subset obtains the result set of the semi-open and semi-closed intervals, which is difficult to operate. Tailset indicates> = headset indicates <

Treeset is an implementation class. Operations that take a range by sorting are defined in the sortedset interface. We recommend that you use sortedset instead of a specific class.

Import Java. util. comparator; import Java. util. hashset; import Java. util. set; import Java. util. treeset; public class treesettest {/*** @ Param ARGs */Public Enum type {going (1), been (2), going_then_been (3); Private int val; private type (INT Val) {This. val = val;} public int getval () {return val;} public void setval (INT Val) {This. val = Val ;}} public static class element {private int memeberid; priva Te int locationid; private type; public element () {} public int getmemeberid () {return memeberid;} public void setmemeberid (INT memeberid) {This. memeberid = memeberid;} public int getlocationid () {return locationid;} public void setlocationid (INT locationid) {This. locationid = locationid;} public type GetType () {return type;} public void settype (type) {This. type = type;} publi C element (INT memeberid, int locationid, type) {super (); this. memeberid = memeberid; this. locationid = locationid; this. type = type ;}@ override public int hashcode () {final int prime = 31; int result = 1; Result = prime * result + locationid; Result = prime * result + memeberid; return result;} @ override public Boolean equals (Object OBJ) {If (this = OBJ) return true; If (OBJ = NULL) Re Turn false; If (getclass ()! = Obj. getclass () return false; element Other = (element) OBJ; If (locationid! = Other. locationid) return false; If (memeberid! = Other. memeberid) return false; return true;} public static void main (string [] ARGs) {treeset <element> elements = new treeset <element> (new comparator <element> () {@ override public int compare (element O1, element O2) {If (o1.gettype (). getval () = o2.gettype (). getval () {return o1.getlocationid ()-o2.getlocationid ();} return o1.gettype (). getval ()-o2.gettype (). getval () ;}}); element e1 = new element (1 11111,294 211, type. going); element e2 = new element (111111,294 212, type. been); element E3 = new element (111111,294 213, type. been); element E4 = new element (111111,294 214, type. going_then_been); elements. add (E1); elements. add (E2); elements. add (E3); elements. add (E4); loadset (elements); system. out. println ("-----------------------"); element from = new element (); from. settype (type. going); element to = new E LEMENT ();. settype (type. going_then_been); element too = new element (); too. settype (type. been); set <element> subset = elements. tailset (too ). headset (to); // set <element> subset = elements. tailset (to); // set <element> subset = elements. tailset (too); // set <element> subset = elements. subset (from, Boolean. false, to, Boolean. false); loadset (subset); system. out. println ("-------------------------"); hashset <element> r Mset = new hashset <element> (); e2.settype (type. going_then_been); rmset. add (E2); e3.settype (type. going_then_been); rmset. add (E3); // In fact, The remove method is called one by one. The reason for removing the method is that if the set contains the following conditions (O = NULL? E = NULL: O. Equals (E) Element E, then remove it. As you can see, remove does not involve sorting operations. Equal works. Elements. removeall (rmset); elements. addall (rmset); loadset (elements);} Private Static void loadset (set <element> set) {for (element: Set) {system. out. println (element. locationid + "|" + element. getType (). name ());}}}
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.