first, set sort (method one)concept: The Java.lang.Comparable interface works when a class has a natural order. The object collection is assumed to be of the same type, which allows the collection to be sorted into natural order. The int compareTo (T obj) method in this interface compares the current instance object with Object obj, returns a negative value if it precedes the object obj, returns 0 if the two objects are in the same position in the sort, or returns a positive value if it is behind the object obj. Implementation essentials: Let the object class that is placed in the container implement the comparable interface. The method that is implemented by CompareTo () determines the order in which objects are arranged. Note: Both TreeSet and TreeMap are collections that have sorting capabilities, and HashSet is a collection with no sorting capabilities. code Example: (Take the TreeSet collection as an example, let the string object in the collection be sorted by the specified rule with the Employee object.) )
Employee object: (The following MySort2 is useful to this class)
public class Employee implements comparable{private String ID; ID number private String name; name private int age; Age private String Department; department static int no = 1; Self-numbering//constructor public employee in employee (string name, int age, string department) {this.id = "No." + (no++); Each given number plus a this.name = Name;this.age = age;this.department = Department;} Constructor (if no department number is set to "no department") public Employee (String name, Int. age) {This (name, age, "no department");} hash function and equals function @overridepublic int hashcode () {final int prime = 31;int result = 1;result = Prime * result + Age;result = Prime * result+ ((department = = null)? 0:department.hashcode ()); result = Prime * result + ((id = = NULL)? 0:id.hash Code ()); result = Prime * result + ((name = = null)? 0:name.hashcode ()); return result; @Overridepublic boolean equals (Object obj) {if (this = = obj) return true;if (obj = = null) return False;if (GetClass ()! = obj . GetClass ()) return false; Employee other = (employee) obj;if (age! = other.age) return false;iF (department = = null) {if (other.department! = null) return false;} else if (!department.equals (other.department)) return F Alse;if (id = null) {if (other.id! = null) return false;} else if (!id.equals (other.id)) return false;if (name = = NULL) {if (Other.name! = null) return false;} else if (!name.equals (other.name)) return False;return true;} The following is a variable get, set function public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String getdepartment () {return department;} public void Setdepartment (String department) {this.department = department;} ToString function @overridepublic String tostring () {return "Employee [id=" + ID + ", name=" + name + ", age=" + age+ ", Departm Ent= "+ department +"] ";} Here is our own Write CompareTo (object o) function @overridepublic int CompareTo (object o) {if (o instanceof Employee) {Employee e= ( Employee) O;return This.age-e.age; Return the difference of the age directly, return greater than, equal to, less than 0. }return 0;}}
MySort1:
Import Java.util.hashset;import Java.util.iterator;import Java.util.treeset;public class MySort1 {public static void Main (string[] args) {HashSet set=new HashSet ();//The method: HashSet cannot customize the ordering, the return value of the Hashcode () method in the Employee class determines the order of the elements. The return value of the Hashcode () method is determined by the data of the current object itself and cannot be compared with other elements //treeset set=new TreeSet ();//The method: TreeSet can customize the sort, The return value of the CompareTo () method in the Employee class determines the order of the elements. The CompareTo () method is determined by the data contrast structure of the current object and the Parameter object, and is written by ourselves//set.add ("ADCF"); It is possible to add a "string" element here, because the CompareTo (object O) method in the employee class can receive any type of parameter object. Set.add ("Jack");//set.add (New String ("ADCF")); it is not feasible to add a "string" element here, because the CompareTo (Object O) method in the String class , you cannot compare the size of an employee object that has already been added to the collection as a parameter to the CompareTo (string str) of the String class. It would be possible to put the sentence before the other add statements, because that would be to invoke the CompareTo (Object O) method in the employee by adding the "string" to the collection first. Set.add (New Employee ("Mike"), Set.add ("Mary"), Iterator it=set.iterator () ; Use iterators to read data//output while (It.hasnext ()) {System.out.println (It.next ());}}}
Operation Result:
First, set sort (method one)
Concept: The Java.util.Comparator interface works when a class has a natural order. The object collection is assumed to be of the same type, which allows the collection to be sorted into natural order. The Compare (T O1, To2) method in this interface: compares the two parameters used to sort. Returns a negative, 0, or positive integer based on the first parameter less than, equal to, or greater than the second parameter.
The point of implementation: let the container join the Comparer object at construction time.
code example: (Take the TreeMap collection as an example to have employees in reverse order.) Chinese sorting problem: The comparison function has no problem with the characters in ASCII code such as English letters and numbers, but the Chinese sort is obviously incorrect. This is mainly in Java in the use of Chinese encoding GB2312 or GBK, char type conversion to int type of process has a relatively large deviation. This deviation is caused by the Compare method, so we can implement the comparator interface ourselves. In addition, the internationalization problem can be solved by collator class.
The Java.text.Collator class, which provides classes and interfaces for handling text, dates, numbers, and messages in a way unrelated to natural language. )
MySort2:
Import Java.text.collationkey;import java.text.collator;import java.util.comparator;import java.util.Iterator; Import Java.util.map;import Java.util.set;import Java.util.treemap;public class MySort2 {public static void main (String [] args) {sort1 (); Use a custom comparer (CompareTo (Object o)) to sort the sort2 (); Chinese sort}//uses a custom comparer (CompareTo (Object o)) to sort private static void Sort1 () {TreeMap map=new TreeMap (New mycmp ());// Give TreeMap a collection plus a comparator mycmp (CompareTo (Object O1,object O2) that we write ourselves, which determines how the elements are sorted by the comparator mycmp (CompareTo (Object O1,object O2)). Add elements to map Map.put ("1002", "Zhou June"), Map.put ("1003", "Liu June"), Map.put ("1012", "Wang June"), Map.put ("1001", "Li June"); Set Entries=map.entryset ();//Returns a set view of the mappings contained in this map iterator it=entries.iterator (); Returns an iterator that iterates over an element in this set//output System.out.println ("Sort1 test:-------------------------------"); while (It.hasnext ()) {// If there are still elements that can be iterated, return truemap.entry en= (map.entry) it.next (); Returns the next element of the iteration System.out.println (En.getkey () + "," +en.getvalue ());}} private static void Sort2 () {TreeMap map=new TreeMap (New MYCMP2 ());//To TreeThe map collection, plus a comparator MyCmp2 (CompareTo (Object O1,object O2) that we wrote ourselves, determines how the elements are sorted by the comparator MYCMP2 (CompareTo (Object O1,object O2)). Add elements to map Map.put ("Zhou June", "1002"), Map.put ("Liu June", "1003"), Map.put ("Wang June", New Employee ("Mike", "Li"), Map.put ("Li June", new Employee ("Rose", 23)); Set Entries=map.entryset ();//Returns a set view of the mappings contained in this map iterator it=entries.iterator (); Returns an iterator that iterates over an element in this set//output System.out.println ("Sort2 test:-------------------------------"); while (It.hasnext ()) {// If there are still elements that can be iterated, return truemap.entry en= (map.entry) it.next (); Returns the next element of the iteration System.out.println (En.getkey () + "," +en.getvalue ());}}} Comparators, (arranged in order from small to large) class MYCMP implements comparator{@Overridepublic int Compare (object O1, Object O2) {return Integer.parseint (O1.tostring ())-integer.parseint (o2.tostring ());}} Class MYCMP2 implements Comparator{collator c=collator.getinstance ();//Get the current default locale for the collator@overridepublic int Compare (object O1, Object O2) {//Converts the String to a list of bits Collationkey Key1=c.getcollationkey that can be compared to other Collationkey bitwise ( O1.tostring ()); Collationkey Key2=c.getcollatioNkey (O2.tostring ()); return Key2.compareto (Key1); Compare this Key1 with Key2}}
Results:
Three, summaryin JDK1.2, there are 14 classes that implement the comparable interface, and the natural sort specified in these classes is as follows:1, bigdecimal,biginteger,byte,double,float,integer,long,short by number size
2. Character by the numeric size of the Unicode values
3, Collationkey by locale-sensitive string sorting
4. Date chronological order
5. File sorted by Unicode value of the fully qualified character of the system-specific path name
6. Objectstreamfield Sort by the Unicode value of the characters in the name
7. String sorted by character Unicode value in string
If a class cannot or does not facilitate the implementation of the Java.lang.Comparable interface, it can provide its own sorting behavior using the method that implements the comparer comparator interface. Similarly, if the default comparable behavior does not meet the engineering needs, you can also provide your own comparator.
Iv. Programming Exercises
Defines a class that has a property of Col, which is a collection type collection that implements the following methods: You can add data to col, modify data, query data, and delete data. That is, the col as a data storage container, the implementation of data deletion and modification of the method.
Code implementation:
Import Java.util.arraylist;import Java.util.collection;public class MyCollection {private Collection col=new ArrayList ();//software engineering, Design method: top-down//Add public boolean Add (Object obj) {return col.add (obj);//Add the specified element to the end of this list}//remove the public boolean Delete (object obj) {return col.remove (obj);//Remove the first occurrence of the specified element (if present) in this list}//modify the public boolean update (Object oldobj,object NEWOBJ) {Object objs[]=col.toarray (); Returns an array containing all the elements in this list col.clear () in the appropriate order (from first to last); Remove all elements in this list for (int i=0;i<objs.length;i++) {if (Objs[i].equals (oldobj)) {objs[i]=newobj; Find the elements that need to be replaced, replace}col.add (Objs[i]) with newobj;} return true;} Find public Collection GetAll () {return col;}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Object-oriented, collection (2)