List 数据去冗 LinkedHashSet

时间:2024-03-28 11:38:03

对List数据的去冗,分两种情况,话不多说,直接上代码:

第一种:

package com.example.mylist;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        List<TestBean> testBeanList=new ArrayList<>();
        testBeanList.add(new TestBean("111","222"));
        testBeanList.add(new TestBean("111","222"));
        testBeanList.add(new TestBean("111","222"));
        testBeanList.add(new TestBean("111","222"));
        testBeanList.add(new TestBean("111","222"));
        testBeanList.add(new TestBean("111","222"));

        LinkedHashSet<TestBean> hashSet = new LinkedHashSet<>(testBeanList);
        List<TestBean> beanList = new ArrayList<>(hashSet);

        Log.e("======",beanList.toString());

    }
}

 

 

 

package com.example.mylist;


import androidx.annotation.Nullable;

public class TestBean {
    private String name;
    private String age;

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

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

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

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

    @Override
    public boolean equals(@Nullable Object obj) {
        TestBean testBean = (TestBean) obj;
        return name.equals(testBean.getName()) && age.equals(testBean.getAge());
    }


    @Override
    public int hashCode() {
        String str = name + age;
        return str.hashCode();
    }
}

 

输出结果如下:

List 数据去冗 LinkedHashSet

第二种情况:

List 数据去冗 LinkedHashSet

输出结果:

List 数据去冗 LinkedHashSet

 

总结:

 

1、LinkedHashSet,底层是链表实现的,是set集合中唯一一个能保证怎么存就怎么取的集合对象
因为是HashSet的子类,所以也是保证元素唯一的,与HashSet的原理一样;

2、在List<TestBean>这种情况下,必须要重写equals()方法和hashCode()方法,至于是为什么,看看源码吧;