java集合-set练习题

练习题


TreeSet练习

题目:定义一个Employee类,该类包含:private 成员变量 name age birthtday,其中birthday为MyDate类的对象。并为每一个属性定义 getter, setter 方法,并重写toString方法输出name age birthday

MyDate类包含: private 成员变量 year month day,并为每一个属性定义getter,setter方法

创建该类的5个对象,并把这些对象放入TreeSet集合中

分别按照以下两种方式对集合中的元素进行排序,并遍历输出

  1. 使Employee实现 Comparable接口,并按name排序
  2. 创建TreeSet时传入 Comparator对象,按生日日期的先后顺序

code
package com.collection.set.practice;

/**
 * 定义一个Employee类,
 * 该类包含:private 成员变量 name age birthtday,
 * 其中birthday为MyDate类的对象。
 * 并为每一个属性定义 getter, setter 方法,
 * 并重写toString方法输出name age birthday
 */
public class Employee implements Comparable{
    private String name;
    private int age;
    private MyDate birthday;

    public Employee(String name, int age, MyDate birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    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 MyDate getBirthday() {
        return birthday;
    }

    public void setBirthday(MyDate birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }

    // 按照姓名排序
    @Override
    public int compareTo(Object o) {
        if(o instanceof Employee){
            Employee e = (Employee)o;
            return this.name.compareTo(e.name);
        }
        //return 0;
        throw new RuntimeException("传入的数据类型不一致");
    }
}
package com.collection.set.practice;

/**
 * MyDate类包含: private 成员变量 year month day,
 * 并为每一个属性定义getter,setter方法
 */
public class MyDate implements Comparable{
    private int year;
    private int month;
    private int day;

    // constructor
    public MyDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    // getter and setter
    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    // toString
    @Override
    public String toString() {
        return "MyDate{" +
                "year=" + year +
                ", month=" + month +
                ", day=" + day +
                '}';
    }

    @Override
    public int compareTo(Object o) {
        if(o instanceof MyDate){
            MyDate m = (MyDate)o;
            //比较年
            int minusYear = this.getYear() - m.getYear();
            if(minusYear != 0){
                return minusYear;
            }
            // 比较月
            int minusMonth = this.getMonth() - m.getMonth();
            if(minusMonth != 0){
                return minusMonth;
            }
            return this.getDay()-m.getDay();
        }
        throw new RuntimeException("not consistant");
    }
}
package com.collection.set.practice;


import com.sun.org.apache.bcel.internal.generic.RETURN;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

/**
 * 创建该类的5个对象,并把这些对象放入TreeSet集合中
 *
 * 分别按照以下两种方式对集合中的元素进行排序,并遍历输出
 *
 * 1. 使Employee实现 Comparable接口,并按name排序
 * 2. 创建TreeSet时传入 Comparator对象,按生日日期的先后顺序
 */
public class EmployeeTest {
    public static void main(String[] args) {
        //test1();
        test2();
    }
    // 问题2:按生日日期的先后排序
    public static void test2(){
        TreeSet set = new TreeSet(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof Employee && o2 instanceof Employee){
                    Employee e1 = (Employee)o1;
                    Employee e2 = (Employee)o2;

                    MyDate b1 = e1.getBirthday();
                    MyDate b2 = e2.getBirthday();
//                    // 方式1:
//                    // 比较年
//                    int minusYear = b1.getYear() - b2.getYear();
//                    if(minusYear != 0){
//                        return minusYear;
//                    }
//                    // 比较月
//                    int minusMonth = b1.getMonth() - b2.getMonth();
//                    if(minusMonth != 0){
//                        return minusMonth;
//                    }
//                    return b1.getDay()-b2.getDay();

                    // 方式2:在MyDate类中实现
                    return b1.compareTo(b2);

                }
                //return 0;
                throw  new RuntimeException("传入的数据类型不一致");
            }
        });

        // CREATE 5 OBJECTS
        Employee e1 = new Employee("joe",24,new MyDate(1997,11,7));
        Employee e2 = new Employee("pepper",67,new MyDate(1945,1,23));
        Employee e3 = new Employee("amy",15,new MyDate(2005,3,6));
        Employee e4 = new Employee("jenny",26,new MyDate(1995,8,20));
        Employee e5 = new Employee("lisa",25,new MyDate(1996,9,7));
        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);
        Iterator iterator =  set.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
    }

//    // 问题1:使用自然排序
//    public static void test1(){
//        TreeSet set = new TreeSet();
//        // CREATE 5 OBJECTS
//        Employee e1 = new Employee("joe",24,new MyDate(1997,11,7));
//        Employee e2 = new Employee("pepper",67,new MyDate(1945,1,23));
//        Employee e3 = new Employee("amy",15,new MyDate(2005,3,6));
//        Employee e4 = new Employee("jenny",26,new MyDate(1995,8,20));
//        Employee e5 = new Employee("lisa",25,new MyDate(1996,9,7));
//        set.add(e1);
//        set.add(e2);
//        set.add(e3);
//        set.add(e4);
//        set.add(e5);
//
//        Iterator iterator =  set.iterator();
//        while(iterator.hasNext()){
//            System.out.println(iterator.next());
//        }
//
    }
}

在List内去除重复数字值,要求尽量简单

hashSet过滤重复数据,效率较高

package com.collection.set;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class Demo01 {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(new Integer(1));
        list.add(new Integer(1));
        list.add(new Integer(2));
        list.add(new Integer(2));
        list.add(new Integer(4));
        List list2 = duplicateList(list);
        for(Object integer:list2){
            System.out.println(integer);
        }
    }

    private static List duplicateList(List list) {
        HashSet set = new HashSet();
        set.addAll(list);
        return new ArrayList(set);
    }
}

面试题

pubilc void test(){
  HashSet set = new HashSet();
  Person p1 = new Person(1001,"AA");
  Person p2 = new Person(1002,"BB");
  set.add(p1);
  set.add(p2);
  p1.name = "CC";
  set.remove(p1);
  System.out.println(set);
  set.add(new Person(1001,"AA"));
  System.out.println(set);
}

先计算 HashCode,再 equals()

code
package com.collection.set.practice;

public class Person {
    int id;
    String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public Person() {
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        if (id != person.id) return false;
        return name != null ? name.equals(person.name) : person.name == null;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }
}
package com.collection.set.practice;

import java.util.HashSet;

public class Test {
    public static void main(String[] args) {
        test1();
    }
    public static void test1(){
        HashSet set = new HashSet();
        Person p1 = new Person(1001,"AA");
        Person p2 = new Person(1002,"BB");
        set.add(p1);
        set.add(p2);
        // System.out.println(set);
        // [Person{id=1001, name='AA'}, Person{id=1002, name='BB'}]
        p1.name = "CC";
        // System.out.println(set);
        // [Person{id=1001, name='CC'}, Person{id=1002, name='BB'}]
        set.remove(p1);
        System.out.println(set);
        // [Person{id=1002, name='BB'}, Person{id=1001, name='CC'}]
        // p1是索引,remove计算P1的哈希值,可能找到的不是开始1001的索引,可能为空
        set.add(new Person(1001,"CC"));
        System.out.println(set);
        // [Person{id=1002, name='BB'}, Person{id=1001, name='CC'}, Person{id=1001, name='CC'}]
        // 拿 1001 和 "CC" 计算哈希值
        set.add(new Person(1001,"AA"));
        System.out.println(set);
        // [Person{id=1002, name='BB'}, Person{id=1001, name='CC'}, Person{id=1001, name='CC'}, Person{id=1001, name='AA'}]
    }
}
  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值