1.set集合的特点
集合的特带都带有增删改查,set集合没有修改,其是无序的。
2.set的遍历方式
遍历方式:
forEach
Iterator
3.集合的去重
3.1字符串
对象形式需要调HashCode和equals方法将其重写
class Xuyahui{ private int id; private String name; public Xuyahui() { // TODO Auto-generated constructor stub } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Xuyahui(int id, String name) { super(); this.id = id; this.name = name; } @Override public String toString() { return "Xuyahui [id=" + id + ", name=" + name + "]"; } @Override public int hashCode() { System.out.println("调用了hashCode方法"); final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { System.out.println("equals方法被调用了"); if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Yinzi other = (Yinzi) obj; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
4.比较器排序
//比较器排序 TreeSet ts2=new TreeSet<>(new Comparator<XYH>() { // @Override // public int compare(XYH o1, XYH o2) { // return o2.getId()-o1.getId(); // } @Override public int compare(XYH o1, XYH o2) { //判断 int num=o2.getMoney()-o1.getMoney(); if(num==0) { return o1.getAge()-o2.getAge(); } return num; } }); //添加 for (Object object : set) { ts2.add(object); } //打印 for (Object object : ts2) { System.out.println("后"+object); } }