import java.util.ArrayList; |
02 |
import java.util.HashSet; |
03 |
import java.util.List; |
09 |
* <br />類描述:set集合針對(duì)String 類型和8大基礎(chǔ)數(shù)據(jù)類型 過濾掉重復(fù)數(shù)據(jù),如果存放的是其他類型對(duì)象,則需要重寫hashCode方法和equals方法,當(dāng)equals 比較相等時(shí),則會(huì)去比較hashCode值 hashCode的值 如果一致的話,則不會(huì)存進(jìn)set |
11 |
public class SetDemo { |
13 |
public static void main(String[] args) { |
14 |
Set<String> nameSet = new HashSet<String>(); |
21 |
for (String name : nameSet){ |
22 |
System.out.print(name + "\t" ); |
25 |
List<String> nameList = new ArrayList<String>(); |
30 |
nameSet.addAll(nameList); |
33 |
for (String name : nameSet){ |
34 |
System.out.print(name + "\t" ); |
38 |
User admin = new User( 1 , "admin" ); |
39 |
User user = new User( 2 , "user" ); |
40 |
User user1 = new User( 2 , "user" ); |
41 |
User admin1 = new User( 3 , "admin" ); |
44 |
Set<User> userSet = new HashSet<User>(); |
50 |
for (User u : userSet){ |
51 |
System.out.print(u.username + u.id + "\t" ); |
54 |
System.out.println(user.equals( null )); |
62 |
protected String username; |
64 |
public User(Integer id, String username){ |
66 |
this .username = username; |
71 |
* 如果對(duì)象類型是User 的話 則返回true 去比較hashCode值 |
74 |
public boolean equals(Object obj) { |
75 |
if (obj == null ) return false ; |
76 |
if ( this == obj) return true ; |
77 |
if (obj instanceof User){ |
81 |
if (user.id == this .id && user.username.equals( this .username)) return true ; |
89 |
* 重寫hashcode 方法,返回的hashCode 不一樣才認(rèn)定為不同的對(duì)象 |
92 |
public int hashCode() { |
94 |
return id.hashCode() * username.hashCode(); |
|