直接来看一道例题,题目来源于廖雪峰老师的网站,这里是对这道题目给出两种解答方式
方法一
//在类里面实现Comparable接口,来解决TreeSet里面的元素是类的对象的情况
/*
在聊天软件中,发送方发送消息时,遇到网络超时后就会自动重发,
因此,接收方可能会收到重复的消息,在显示给用户看的时候,需要首先去重。
请练习使用Set去除重复的消息
*/
import java.util.*;
public class SetDemo3 {
public static void main(String[] args) {
List<Message> received = new ArrayList<>();
received.add(new Message(1, "Hello!"));
received.add(new Message(2, "发工资了吗?"));
received.add(new Message(2, "发工资了吗?"));
received.add(new Message(3, "去哪吃饭?"));
received.add(new Message(3, "去哪吃饭?"));
received.add(new Message(4, "Bye"));
List<Message> displayMessage = process(received);
for(Message m:displayMessage){
System.out.println(m.text);
}
}
static List<Message> process(List<Message> received){
Set<Message> set = new TreeSet<>();
List<Message> l = new ArrayList<>();
for(Message m:received){
set.add(m);
}
for(Message m:set){
l.add(m);
}
return l;
}
}
class Message implements Comparable<Message>{
public final int sequence ;
public final String text;
public Message(int s,String t){
sequence = s;
text = t;
}
public int compareTo(Message m){
if(this.sequence==m.sequence){
return 0;
}
return this.sequence>m.sequence ? 1 : -1;
}
}
方法二
建立一个Set集合,用来去重,建立一个List集合,用来存放去重后的元素
set.add() //如果添加成功会返回一个true,添加失败则会返回false
package test.SetDemo;
import java.util.*;
public class SetDemo3 {
public static void main(String[] args) {
List<Message> received = new ArrayList<>();
received.add(new Message(1, "Hello!"));
received.add(new Message(2, "发工资了吗?"));
received.add(new Message(2, "发工资了吗?"));
received.add(new Message(3, "去哪吃饭?"));
received.add(new Message(3, "去哪吃饭?"));
received.add(new Message(4, "Bye"));
List<Message> displayMessage = process(received);
for(Message m:displayMessage){
System.out.println(m.text);
}
}
static List<Message> process(List<Message> received){
Set<Integer> set = new HashSet<>();
List<Message> r = new ArrayList<>();
for(Message l : received){
if(set.add(l.sequence)){
r.add(l);
}
}
return r;
}
}
class Message {
public final int sequence ;
public final String text;
public Message(int s,String t){
sequence = s;
text = t;
}
}