1.先重写实体类中的equals()方法和hashCode()方法,
import java.util.Objects;
public class Bluetooth {
private String name;
private String address;
private int type;
//...其他代码
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bluetooth bluetooth = (Bluetooth) o;
return type == bluetooth.type &&
Objects.equals(name, bluetooth.name) &&
Objects.equals(address, bluetooth.address);
}
@Override
public int hashCode() {
String in = name + address + type;
return in.hashCode();
}
}
2.定义的List和Set
private List<Bluetooth> mStrListBle = new ArrayList<>();//包含了重复元素
private Set<Bluetooth> mBluetoothSetBle = new HashSet<>();//准备用来去掉重复元素的Set
3.去掉mStrListBle中的重复对象
//set集合保存的是不同对象的地址,多个相同对象都指向同一地址
mBluetoothSetBle.addAll(mStrListBle);