天天看点

Set集合两道面试题Set

Set

去重
package com.xing.java;

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

/**
 * @User: Vtop-FadeAway
 * @Date: 2020/6/29
 * @Time: 19:32
 * ( ̄▽ ̄)~* -> ❥(^_-)
 * You had me at hello.
 */
public class Interview1 {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(new Integer(1));
        list.add(new Integer(3));
        list.add(new Integer(3));
        list.add(new Integer(5));
        list.add(new Integer(5));

        List list2 = duplicateList(list);

        for (Object integer : list2) {
            System.out.println("integer = " + integer);
        }  // 1 3 5
    }

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

           
add & remove
package com.xing.java;

import java.util.HashSet;
import java.util.Objects;

/**
 * @User: Vtop-FadeAway
 * @Date: 2020/6/29
 * @Time: 19:50
 * ( ̄▽ ̄)~* -> ❥(^_-)
 * You had me at hello.
 */
public class Interview2 {
    public static void main(String[] args) {
        HashSet set = new HashSet();
        ABC aa = new ABC(101, "AA");
        ABC bb = new ABC(102, "BB");

        set.add(aa);
        set.add(bb);
        aa.s = "CC";
        set.remove(aa);
        System.out.println("set = " + set);
        set.add(new ABC(101, "CC"));
        System.out.println("set = " + set);
        set.add(new ABC(101, "AA"));
        System.out.println("set = " + set);
    }
}

class ABC {
    int id;
    String s;

    public ABC(int id, String s) {
        this.id = id;
        this.s = s;
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ABC abc = (ABC) o;
        return id == abc.id &&
                Objects.equals(s, abc.s);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, s);
    }
}