Set接口下的集合

Set接口下的集合

<>范型

1.HashSet

  HashSet set = new HashSet();
set.add("aa");
set.add(111);
set.add("bb");
set.add("aa");
set.add("cc");

System.out.println(set.size());
//因为是无序的,所以不能用for循环读取,而是用增强for循环(foreach循环:快捷键alt + /)或者迭代器Iterator
for(Object obj : set) {
System.out.println(obj);
}
Iterator it = set.iterator();
while(it.hasNext()) {
Object obj = it.next();
System.out.println(obj);
}

集合中也可以添加其它的类,但是Set下的集合是无序的,读取时不方便,所以必须使用包装类

  public class Student {
private int id;
private String name;
private String address;
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Student() {
}
public Student(int id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", address=" + address + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (address == null) {
if (other.address != null)
return false;
} else if(!address.equals(other.address))
return false;
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;
}


  public class Worker {
private String name;
private String type;
private double salary;

public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Worker() {
}
public Worker(String name, String type, double salary) {
this.name = name;
this.type = type;
this.salary = salary;
}


 

  public class Test {

public static void main(String[] args) {

Student s1 = new Student(1,"张三","成都");
Student s2 = new Student(2,"李四","绵阳");

Worker w1 = new Worker("张师傅","木工",8000);
Worker w2 = new Worker("王师傅","漆工",10000);

ArrayList list = new ArrayList();
list.add(s1);
list.add(s2);
list.add(w1);
list.add(w2);

for(Object obj : list) {
if(obj instanceof Student) {
Student stu = (Student)obj;
System.out.println(stu.getId() + "===" + stu.getName() + "===" + stu.getAddress());
}
else if(obj instanceof Worker) {
Worker w = (Worker)obj;
System.out.println(w.getName() +":" + w.getType() + ":" + w.getSalary());
}
else {
System.out.println(obj);
}
}


}

 

  public static void main(String[] args) {

Student s1 = new Student(1,"张三","成都");
Student s2 = new Student(2,"李四","绵阳");

Worker w1 = new Worker("张师傅","木工",8000);
Worker w2 = new Worker("王师傅","漆工",10000);
//父类型引用指向子类型对象
List<Student> list = new LinkedList<Student>();

list.add(s1);
list.add(s2);

for (int i = 0; i < list.size(); i++) {
Student s = list.get(i);
System.out.println(s);
}
List<Worker> list2 = new  LinkedList<Worker>();
list2.add(w1);
list2.add(w2);
for(int i = 0; i<list2.size(); i++){
Worker w = list2.get(i);
System.out.println(w);
}
}

 

基本数据类型的泛型集合,必须使用包装类

  public static void main(String[] args) {
//基本数据类型的泛型集合,必须使用包装类
List<Integer> list = new ArrayList<Integer>();
list.add(111);
list.add(222);
list.add(333);
list.add(444);

}

 

  public static void main(String[] args) {
Student s1 = new Student(1,"张三","成都");
Student s2 = new Student(1,"张三","成都");
Worker w1 = new Worker("张师傅","木工",8000);
Worker w2 = new Worker("张师傅","木工",8000);

//s2 = s1;

System.out.println(s1.equals(s2)); //true
System.out.println(s1 == s2);//false

System.out.println(s1.equals(s2));//true
System.out.println(s1 == s2);;//false

Set<Student> sets = new HashSet<>();
sets.add(s1);
sets.add(s2);

for (Student student : sets) {
System.out.println(student);//Student [id=1, name=张三, address=成都
}
Set<Worker> sets1 = new HashSet<>();
sets1.add(w1);
sets1.add(w2);
for (Worker worker : sets1) {
System.out.println(worker);//Worker [name=张师傅, type=木工, salary=8000.0
//Worker [name=张师傅, type=木工, salary=8000.0
}
}
//因为Student类中重写了HashCode()和equals()方法

2.TreeSet

  public static void main(String[] args) {
TreeSet<Integer> treeSet = new TreeSet<Integer>();
treeSet.add(1);
treeSet.add(2);
treeSet.add(3);
treeSet.add(4);
treeSet.add(5);

for (Integer integer : treeSet) {
System.out.println(integer);
}

 

  public static void main(String[] args) {
Set<String> treeSet = new TreeSet<String>();
treeSet.add("aa");
treeSet.add("bb");
treeSet.add("cc");
treeSet.add("dd");
treeSet.add("ee");

for (String ss : treeSet) {
System.out.println(ss);
}
}

TreeSet要求,放入进去的对象必须要实现Comparable接口 并且实现Comparable接口的compareTo方法

  //TreeSet要求,放入进去的对象必须要实现Comparable接口
//并且实现Comparable接口的compareTo方法
Student s1 = new Student(1,"张三","成都");
Student s2 = new Student(2,"李四","绵阳");
Student s3 = new Student(3,"王五","德阳");
Student s4 = new Student(4,"赵六","广元");
TreeSet<Student> treeSet = new TreeSet<Student>();
treeSet.add(s2);
treeSet.add(s1);
treeSet.add(s4);
treeSet.add(s3);

for (Student ss : treeSet) {
System.out.println(ss);
}
因此需在Student类中让其public class Student implements Comparable<Student>
且实现public int compareTo(Student o) {
//注意,下面并不一定返回是1或者-1
//只要是正数或者负数就可以了
if(this.id > o.id) {
return 1;
}
else if(this.id < o.id) {
return -1;
}
else {
return 0;
}
}

Set转换为List

  //Set转换为List
public static void main(String[] args) {
Student s1 = new Student(1,"张三","成都");
Student s2 = new Student(2,"李四","绵阳");
Student s3 = new Student(3,"王五","德阳");
Student s4 = new Student(4,"赵六","广元");
Set<Student> sets = new HashSet<Student>();
sets.add(s1);
sets.add(s2);
sets.add(s3);
  sets.add(s4);

for (Student student : sets) {
System.out.println(student);
}

System.out.println("==========================");

List<Student> lists = new ArrayList<>(sets);

for (int j = 0; j < lists.size(); j++) {
System.out.println(lists.get(j));
}
   Collections.sort(lists);

System.out.println("============Collections.sort==============");
for (int j = 0; j < lists.size(); j++) {
System.out.println(lists.get(j));
}


System.out.println("===========Collections.sort(集合对象, 实现了Comparator的对象);===============");
Collections.sort(lists, new StudentCompare());

for (int j = 0; j < lists.size(); j++) {
System.out.println(lists.get(j));
}
}

注意: Collection和 Collections的区别:

都是在java.util包下面

Collection是所有集合的接口

Collections 是一个包装类,此类不能实例化,就像一个工具类

Comparable和Comparator的区别:

Comparable和Comparator都是用于比较数据的大小的

Comparable:在java.lang包下。Comparable接口中只有一个方法:compareTo(),因此实现Comparable接口需要重写compareTo方法。且compareTo()中只有一个参数,所以一般情况下我们会在定义类的时候有排序的需求,就要实现此接口。

  public class UserComparable implements Comparable<UserComparable> {
   private String name;
   private int age;

   public UserComparable(String name, int age) {
       this.name = name;
       this.age = age;
  }
   @Override
   public String toString() {
       return "UserComparable{" +
               "name='" + name + '\'' +
               ", age=" + age +
               '}';
  }

   @Override
   public int compareTo(UserComparable o) {
       if (this.name.compareTo(o.name)==0){
           if (this.age == o.age){
               return 0;
          }else if (this.age >o.age){
               return 1;
          }else {
               return -1;
          }
      }else if (this.name.compareTo(o.name)>0){
           return 1;
      }else {
           return -1;
      }
  }

public static void main(String[] args) {
       List<UserComparable> list = new ArrayList<UserComparable>();
       list.add(new UserComparable("gol",21));
       list.add(new UserComparable("gol",19));
       list.add(new UserComparable("xiao",21));
       list.add(new UserComparable("long",21));
       System.out.println("排序前:"+list);//[UserComparable{name='gol', age=21}, UserComparable{name='gol', age=19}, UserComparable{name='xiao', age=21}, UserComparable{name='long', age=21}]
       //排序规则:先按name排序,若name相等则再比较age
       Collections.sort(list);
       System.out.println("排序后:"+list);//[UserComparable{name='gol', age=19}, UserComparable{name='gol', age=21}, UserComparable{name='long', age=21}, UserComparable{name='xiao', age=21}]
  }
}

Comparator:在java.uitl包下。Comparator接口中方法很多,但是我们只需要实现一个,也是最重要的一个compare().该方法有两个参数。只需要新定义一个比较器(类)来实现Comparator,重写compare方法并将User对象传进去。

  public class User {
   private String name;
   private int age;

   public User(String name, int age) {
       this.name = name;
       this.age = age;
  }

   @Override
   public String toString() {
       return "User{" +
               "name='" + name + '\'' +
               ", age=" + age +
               '}';
  }
 
   public static void main(String[] args) {
       List<User> list = new ArrayList<User>();
       list.add(new User("gol", 21));
       list.add(new User("gol", 19));
       list.add(new User("xiao", 21));
       list.add(new User("long", 21));
       System.out.println("排序前:" + list);//[UserComparable{name='gol', age=21}, UserComparable{name='gol', age=19}, UserComparable{name='xiao', age=21}, UserComparable{name='long', age=21}]
       //排序规则:先按name排序,若name相等则再比较age
       //创建比较器对象
       Comparator comparator = new UserComparator();
       Collections.sort(list,comparator);
       System.out.println("排序后:" + list);//[UserComparable{name='gol', age=19}, UserComparable{name='gol', age=21}, UserComparable{name='long', age=21}, UserComparable{name='xiao', age=21}]
  }
  static class UserComparator implements Comparator<User> {

       @Override
       public int compare(User o1, User o2) {
           if (o1.name.compareTo(o2.name) == 0) {
               if (o1.age == o2.age) {
                   return 0;
              } else if (o1.age > o2.age) {
                   return 1;
              } else {
                   return -1;
              }

 

你可能感兴趣的:(Set接口下的集合)