用TreeSet集合来装一个自定义对象StudentEntity

时间:2022-09-03 00:14:15

/*
* 需求 :
* 1用TreeSet集合来装一个自定义对象StudentEntity
* 2.并用名字来排序
* 3。去除完全重复的数据
* 分析:
* 1.先写一个实体类StudentEntity
* 2.再写一个测试类TreeSetDemo2
* 3.通过StudentEntity构造方法创建10个StudentEntity对象,有一些数据是相同的
* 4.添加StudentEntity到集合TreeSet中
* 5.通过在StudentEntity类中重写Comparable的compareTo()方法来实现以姓名排序
*/

  实体类StudentEntity

package com.ma.treeset;

import java.util.Comparator;
/**
 * 实体类
 * @author ma
 *
 */
public class StudentEntity  implements Comparable<StudentEntity>{
	
	private String name;
	private int age;
	
	public StudentEntity() {
		super();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

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

	@Override
	public String toString() {
		return "StudentEntity [name=" + name + ", age=" + age + "]";
	}

	@Override
	public int compareTo(StudentEntity se) {
		//判断名字长度是否相等
		int num = this.getName().length() - se.getName().length();
	
		//用compareTo()方法判断姓名是否是一样的
		int num1 = num==0 ? this.getName().compareTo(se.getName()) : num;
		int num2 = num1==0 ? this.getAge() - se.getAge() : num1;
		
		return num2;
	}
	
	
	
}

  测试类TreeSetDemo2:

package com.ma.treeset;

import java.util.TreeSet;



/**
 * 测试类
 * @author ma
 *
 */
public class TreeSetDemo2 {
	
	public static void main(String[] args) {
		
		//创建一个TreeSet对象
		TreeSet<StudentEntity> ts = new TreeSet<StudentEntity>();
		
		//创建10个StudentEntity对象
		StudentEntity s1 = new StudentEntity("张三1",111);
		StudentEntity s2 = new StudentEntity("张三3",112);
		StudentEntity s3 = new StudentEntity("张三2",113);
		StudentEntity s4 = new StudentEntity("张三8",114);
		StudentEntity s5 = new StudentEntity("张三5",115);
		StudentEntity s6 = new StudentEntity("张三6",116);
		StudentEntity s7 = new StudentEntity("张三7",117);
		StudentEntity s8 = new StudentEntity("张三4",118);
		StudentEntity s9 = new StudentEntity("张三1",119);
		StudentEntity s10 = new StudentEntity("张三1",111);
		

		//添加数据
		ts.add(s1);
		ts.add(s2);
		ts.add(s3);
		ts.add(s4);
		ts.add(s5);
		ts.add(s6);
		ts.add(s7);
		ts.add(s8);
		ts.add(s9);
		ts.add(s10);

		//遍历输出
		for(StudentEntity s : ts){
			System.out.println(s);
		}
		
	}

}

  输出结果:

    StudentEntity [name=张三1, age=111]
    StudentEntity [name=张三1, age=119]
    StudentEntity [name=张三2, age=113]
    StudentEntity [name=张三3, age=112]
    StudentEntity [name=张三4, age=118]
    StudentEntity [name=张三5, age=115]
    StudentEntity [name=张三6, age=116]
    StudentEntity [name=张三7, age=117]
    StudentEntity [name=张三8, age=114]