import java.util.ArrayList; |
02 |
import java.util.HashSet; |
03 |
import java.util.List; |
09 |
* <br />类描述:set集合针对String 类型和8大基础数据类型 过滤掉重复数据,如果存放的是其他类型对象,则需要重写hashCode方法和equals方法,当equals 比较相等时,则会去比较hashCode值 hashCode的值 如果一致的话,则不会存进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 |
* 如果对象类型是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 不一样才认定为不同的对象 |
92 |
public int hashCode() { |
94 |
return id.hashCode() * username.hashCode(); |
|