Set Exercises-set and Set
We know that list stores elements that are not sequential.
Set stores unordered and unique elements.
Here is an example:
package CollectionPart;import java.util.HashSet;import java.util.Set;public class HashSet1 { public static void main(String[] args) { Set mySet = new HashSet(); mySet.add("df"); mySet.add("df"); System.out.println(mySet.size()); for (Object object : mySet) { System.out.println(object); } }}
Running result:
1
Df
This fully demonstrates that the elements stored in the set are unique.
The following code will reflect a problem:
package CollectionPart;import java.util.HashSet;import java.util.Set;public class HashSet1 { public static void main(String[] args) { Set mySet = new HashSet(); mySet.add("df"); mySet.add("df"); Employee_1 e1 = new Employee_1("1","lifei",23,"2013-02-09"); Employee_1 e2 = new Employee_1("1","lifei",23,"2013-02-09"); mySet.add(e1); mySet.add(e2); System.out.println(mySet.size()); for (Object object : mySet) { System.out.println(object); } }}
Running result:
3
Df
Employee_1 [employeeId = 1, employeeName = lifei, employeeAge = 23, employeeHireDate = 2013-02-09]
Employee_1 [employeeId = 1, employeeName = lifei, employeeAge = 23, employeeHireDate = 2013-02-09]
The elements we store are exactly the same, but the results seem unsatisfactory. Isn't it true that all elements in the set are stored differently? e1 and e2 are obviously the same object.
In this case, we need to consider the criteria used by the set to determine whether the elements are equal.
When you move the cursor over the add method, a prompt is displayed:
Adds the specified element to this set if it is not already present. More formally, adds the specified elementETo this set if this set contains no elementE2Such that(E = null? E2 = null: e. equals (e2 )). If this set already contains the element, the call leaves the set unchanged and returnsFalse.
It is necessary to read this description: add a specific element to the set, if such an element does not exist. Generally, when an element EIS added to the current set, if there is no e2 in this set, [compare with the equals function] If this element already exists, the set is not modified and false is returned when the add method is called.
// There are two points to try: 1. The number of null values can be stored, which is 1 in the description. 2. When an existing element is added for the second time, an error is reported, instead of overwriting the value for the first time. This is simply what we can imagine, because overwrite is added once, and more operations are generated. It is not as efficient as not allowed to be added.
Package CollectionPart; import java. util. hashSet; import java. util. set; public class HashSet1 {public static void main (String [] args) {Set mySet = new HashSet (); mySet. add ("df"); boolean add = mySet. add ("df"); System. out. println ("successful addition:" + add); Employee_1 e1 = new Employee_1 ("1", "lifei", 23, "2013-02-09 "); employee_1 e2 = new Employee_1 ("1", "lifei", 23, "2013-02-09"); mySet. add (e1); mySet. add (e2); System. out. println (mySet. size (); for (Object object: mySet) {System. out. println (object);} mySet. add (null); boolean add2 = mySet. add (null); System. out. println ("whether to add successfully:" + add2 + ", the number of elements in the set:" + mySet. size ());}}
Running result:
Added successfully: false
3
Df
Employee_1 [employeeId = 1, employeeName = lifei, employeeAge = 23, employeeHireDate = 2013-02-09]
Employee_1 [employeeId = 1, employeeName = lifei, employeeAge = 23, employeeHireDate = 2013-02-09]
Added successfully: false. Number of elements in the set: 4
Next we have to deal with this equals problem, so we can go back and study the comparison of the equals method for the element in this set. After all, e1 and e2 are a person. Try to separate them. View the equals method in the default Employee
There is no equals method in the employee class we wrote, which indicates that this is inherited. Therefore, when we think about equals, we get a function like this:
@Override public boolean equals(Object obj) { // TODO Auto-generated method stub return super.equals(obj); }
Place the cursor over equals to get the following description:
Indicates whether some other object is "equal to" this one.
TheequalsMethod implements an equivalence relation on non-null object references:
- It isReflexive: For any non-null reference value
x,x.equals(x)Shocould returntrue.
- It isSymmetric: For any non-null reference values
xAndy,x.equals(y)Shocould returntrueIf and only ify.equals(x)Returnstrue.
- It isTransitive: For any non-null reference values
x,y, Andz, Ifx.equals(y)ReturnstrueAndy.equals(z)Returnstrue, Thenx.equals(z)Shocould returntrue.
- It isConsistent: For any non-null reference values
xAndy, Multiple invocationsx.equals(y)Consistently returntrueOr consistently returnfalse, Provided no information used inequalsComparisons on the objects is modified.
- For any non-null reference value
x,x.equals(null)Shocould returnfalse.
TheequalsMethod for classObjectImplements the most discriminating possible equivalence relation on objects; that is, for any non-null reference valuesxAndy, This method returnstrueIf and only ifxAndyRefer to the same object (x == yHas the valuetrue).
Note that it is generally necessary to overridehashCodeMethod whenever this method is overridden, so as to maintain the general contract forhashCodeMethod, which states that equal objects must have equal hash codes.
Thank you,
Determine whether other objects are equal to the current object.
Reflective? Reflexive? : X. equals (s) should return true for any value.
Symmetry: for non-null values x and y, if x. equals (y) returns true, true is returned only when y. equals (x) is returned.
Passed: for non-null values x, y, and z, if x. equals (y) returns true, y. equals (z) returns true, then x. equals (z) should also return true.
Consistency? : No matter how it is called, the results should be consistent, either true or false. When two non-null values, x, y, in this continuous comparison process, it is always not modified.
The return value for non-null values x and x. equals (null) should be false.
The equals method is used to describe whether two objects in the object class are equal. If the return result of non-null value x and y is true, x and y execute the same entity.
Note: The hashCode method should also be rewritten as long as the equals method is overwritten. To maintain the overall relationship between the hashCode method and to indicate that the same object has the same hash code.
Therefore, this is the point of attention of the Set. If you use the Set, you must remember to rewrite the equals and hashCode methods. [Fortunately, both methods can be automatically generated .]
In ssh, if you use many-to-many methods, remember to rewrite these two methods.
However, the focus is still unclear. That is why e1 is not equal to e2.
We can use the shortcut key ctrl + left mouse button to find its implementation method:
public boolean equals(Object obj) { return (this == obj); }
Found. They call such a statement at the underlying layer. The question is, what is the comparison between this and what is this? We usually always output the current object when verifying whether there is a null pointer. The comparison is the address value of the current object returned. If the value is not equal, the two are considered to be not equal. Well, now we think that if the IDs are the same and the names are the same, these two elements are an entity. In fact, it is best to include all attributes, however, some attributes of the later system that have uniqueness constraints can be used as the identifier of whether the two entities are equal.
The Set must note that this one must override the equals () method and hashCode () method, and nothing else.
Exercise: print the employee name and gender and use the iterator to traverse
The employee's field includes the employee ID, name, age, and start time.
Since the employee class is changed, you may wish to write a new entity class.
// Copy it when writing, so output the name and age.
Package CollectionPart;/*** to Set the contact, two methods are rewritten more than Employee_1 **/public class Employee_2 {private String employeeId; private String employeeName; private int employeeAge; private String employeeHireDate;/* It is stored as String type and set to date format in the database. Then use Date today = new Date (); SimpleDateFormat fm = new SimpleDateFormat ("YYYY-MM-dd"); to do */public String getEmployeeId () {return employeeId ;} public void setEmployeeId (String employeeId) {this. employeeId = employeeId;} public String getEmployeeName () {return employeeName;} public void setEmployeeName (String employeeName) {this. employeeName = employeeName;} public int getEmployeeAge (){ Return employeeAge;} public void setEmployeeAge (int employeeAge) {this. employeeAge = employeeAge;} public String getEmployeeHireDate () {return employeeHireDate;} public void setEmployeeHireDate (String employeeHireDate) {this. employeeHireDate = employeeHireDate;} @ Override public String toString () {return "Employee_1 [employeeId =" + employeeId + ", employeeName =" + employeeName + ", employe EAge = "+ employeeAge +", employeeHireDate = "+ employeeHireDate +"] ";} public Employee_2 (String employeeId, String employeeName, int employeeAge, String employeeHireDate) {super (); this. employeeId = employeeId; this. employeeName = employeeName; this. employeeAge = employeeAge; this. employeeHireDate = employeeHireDate;} public Employee_2 () {super () ;}@ Override public int hashCode () {final int Prime = 31; int result = 1; result = prime * result + employeeAge; result = prime * result + (employeeHireDate = null )? 0: employeeHireDate. hashCode (); result = prime * result + (employeeId = null )? 0: employeeId. hashCode (); result = prime * result + (employeeName = null )? 0: employeeName. hashCode (); return result ;}@ Override public boolean equals (Object obj) {if (this = obj) return true; if (obj = null) return false; if (getClass ()! = Obj. getClass () return false; Employee_2 other = (Employee_2) obj; if (employeeAge! = Other. employeeAge) return false; if (employeeHireDate = null) {if (other. employeeHireDate! = Null) return false;} else if (! EmployeeHireDate. equals (other. employeeHireDate) return false; if (employeeId = null) {if (other. employeeId! = Null) return false;} else if (! EmployeeId. equals (other. employeeId) return false; if (employeeName = null) {if (other. employeeName! = Null) return false;} else if (! EmployeeName. equals (other. employeeName) return false; return true ;}
}
Package CollectionPart; import java. util. hashSet; import java. util. iterator; import java. util. set; public class HashSetPractise_1 {public static void main (String [] args) {Employee_2 e1 = new Employee_2 ("dept0000001", "lifei", 23, "2016-02-05 "); employee_2 e2 = new Employee_2 ("dept0000001", "lifei", 23, "2016-02-05"); Employee_2 e3 = new Employee_2 ("dept0000002", "life2", 24, "2016-03-05"); Employee_2 e4 = new Employee_2 ("dept3_001", "life3", 28, "2015-03-05"); Set <Employee_2> mySet = new HashSet <Employee_2> (); mySet. add (e1); mySet. add (e2); mySet. add (e3); mySet. add (e4); Iterator <Employee_2> iterator = mySet. iterator (); System. out. println ("Number of employees:" + mySet. size (); while (iterator. hasNext () {maid = iterator. next (); System. out. println ("current employee:" + employee_2.getEmployeeName () + ", age:" + employee_2.getEmployeeAge ());}}}
Running result:
Number of employees: 3
Current EMPLOYEE: life3, Age: 28
Current EMPLOYEE: lifei, age: 23
Current EMPLOYEE: life2, age: 24
One thing we find is indeed unordered.