java中List对象列表去重或取出以及排序

您所在的位置:网站首页 javalist去重复对象 java中List对象列表去重或取出以及排序

java中List对象列表去重或取出以及排序

2023-08-04 10:08| 来源: 网络整理| 查看: 265

面试碰到几次list的去重和排序。下面介绍一种做法:

1. list去重1.1 实体类Student

List容量10k以上,要求去重复。这里Student的重复标准是属性相同,因此需要重写equals和hashcode方法,不知道有几个可以手写出来。

student的equals方法:

public void equals(Object o){ if(this == o) retun true; if(!(o instanceof Student)) return false; Student stu = (Studend)o; if(id!=stu.id) return false; if(age!=stu.age) return false; return name!=null ? name.equals(stu.name) : stu.name ==null; }

这里只要记住宗旨是比较Student的属性即可,如果属性相同则相等。先考虑地址相等,然后类型匹配instanceof。接下来是各种属性,int属性直接双等号比较,String类型需要判断是否为null,如果是null则都是null返回true,如果不是null则比较equals。

student的hashcode方法:

public int hashCode(){ int result = id; reuslt = 31*id +(name!=null?name.hashCode():0); reuslt = 31*age; return reuslt; }

hashCode是为了hash表计算做辅助,方便快速查找。因此hash算法的结果要尽量的散列。这里用到31,这个31在别的博客中看到的原因是这样的:obj*31==obj



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3