集合操作(三)Set

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

Set集合

HashSet

    哈希表保证元素的唯一性依赖于两个方法一个是hashCode方法一个是equals方法

    如果两个对象的hashCode值相同,并且调用该对象的equals方法返回的是true的时候,那么就说明两个对象是相同的

结论:

    HashSet集合存储元素,保证元素的唯一性,需要让这个元素重写hashCode和equals方法

遍历hash表

(1)Student.java

public class Student {private String name;private int age;public Student() {super();// TODO Auto-generated constructor stub}public Student(String name, int age) {super();this.name = name;this.age = age;}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;}
//重写hashCode方法@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + age;result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}
//重写equals方法@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Student other = (Student) obj;if (age != other.age)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}}

(2)hashSetTest.java

import java.util.HashSet;public class hashSetTest {public static void main(String[] args) {Student s1 = new Student("卫杰",21);Student s2 = new Student("宋玉",22);Student s3 = new Student("黄英",18);Student s4 = new Student("卫杰",21);HashSet<Student> hs = new HashSet<Student>();hs.add(s1);hs.add(s2);hs.add(s3);hs.add(s4);for(Student s:hs){System.out.println(s.getName()+"---"+s.getAge());}}
}

TreeSet

TreeSet: 可以对元素进行排序 , 而排序分为两种方式一种自然排序 ,一种比较器排序

              那么我们到底使用的自然排序还是比较器排序主要取决于构造方法

     public TreeSet() 使用的是自然排序

      public TreeSet(Comparator comparator) 使用比较器排序

一.使用自然排序

(1)Person.java

public class Person implements Comparable<Person> {private String name;private int age;public Person() {super();// TODO Auto-generated constructor stub}public Person(String name, int age) {super();this.name = name;this.age = age;}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + "]";}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;}//采用自然排序方式进行排序,实现compareTo方法@Overridepublic int compareTo(Person o) {// TODO Auto-generated method stub//比较年龄int num = this.age -o.age;int num2 = (num == 0) ? this.name.compareTo(o.name) : num;return num2;}}

(2)TreeSetDemo1.java

* 根据年龄对Person类的对象进行排序*/
import java.util.TreeSet;public class TreeSetDemo1 {public static void main(String[] args) {//创建person对象Person p1 = new Person("昭明",22);Person p2 = new Person("清风",16);Person p3 = new Person("兰亭",23);Person p4 = new Person("清风",24);Person p5 = new Person("兰亭集",23);//创建TreeSet对象TreeSet<Person> tr = new TreeSet<Person>();	tr.add(p5);tr.add(p4);tr.add(p3);tr.add(p2);tr.add(p1);for(Person t : tr){System.out.println(t.getName()+"-------"+t.getAge());}}
}/*清风-------16
昭明-------22
兰亭-------23
兰亭集-------23
清风-------24*/

二.使用比较器进行排序

(1)Person.java

public class Person {private String name;private int age;public Person() {super();// TODO Auto-generated constructor stub}public Person(String name, int age) {super();this.name = name;this.age = age;}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;}}

(2)MyComparater.java

//使用比较器进行比较
import java.util.Comparator;public class MyComparater implements Comparator<Person> {@Overridepublic int compare(Person arg0, Person arg1) {// TODO Auto-generated method stub//按照名字长度进行比较int num = arg0.getName().length()-arg1.getName().length();//判断名字是否相同int num2 =(num==0)?arg0.getName().compareTo(arg1.getName()):num;//比较年龄大小int num3 = (num2==0)?arg0.getAge()-arg1.getAge():num2;return num3;}}

(3)TreeSetDemo2.java

 */
import java.util.TreeSet;
import java.util.Comparator;public class TreeSetDemo2 {public static void main(String[] args) {//自定义Person类的对象Person p1 = new Person("Bob",23);Person p2 = new Person("Wiki",22);Person p3 = new Person("Wiki",21);Person p4 = new Person("go",19);Person p5 = new Person("Link",22);//创建TreeSet集合对象TreeSet<Person> tr = new TreeSet<Person>(new MyComparater());//使用内部类实现比较器排序
//			TreeSet<Person> tr = new TreeSet<Person>(new Comparator<Person>(){
//				public int compare(Person arg0, Person arg1) {
//					// TODO Auto-generated method stub
//					//按照名字长度进行比较
//					int num = arg0.getName().length()-arg1.getName().length();
//					//判断名字是否相同
//					int num2 =(num==0)?arg0.getName().compareTo(arg1.getName()):num;
//					//比较年龄大小
//					int num3 = (num2==0)?arg0.getAge()-arg1.getAge():num2;
//					return num3;
//				}
//			});//使用内部类比较器进行比较//将Person类的对象加入TreeSet集合tr.add(p5);tr.add(p4);tr.add(p3);tr.add(p2);tr.add(p1);for(Person t:tr){System.out.println(t.getName()+"---"+t.getAge());}}
}
/** go---19 Bob---23 Link---22 Wiki---21 Wiki---22*/


转载于:https://my.oschina.net/CentralD/blog/608712

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/543703.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mcq 队列_MCQ | 软件程序分析工具和组件分类| 免费和开源软件

mcq 队列Q1. Which of the following analysis methods come under Static Analysis Tools? Q1。 静态分析工具包含以下哪些分析方法&#xff1f; Code Walkthrough 代码演练 Code Inspection 代码检查 None of the Above 以上都不是 Both a. & b. 两者都 &#xff06;b。…

samba部署小结

[rootOracle ~]# yum install samba-swat -y[rootOracle ~]# yum install samba-client 客户端工具主配置文件&#xff1a;[rootOracle ~]# cat /etc/samba/smb.conf |grep -v "#"|grep -v "^$"|grep -v ";"[global]workgroup …

JAVA调用动态链接库

上一篇《JAVA本地接口&#xff08;JNI&#xff09;》中介绍了JAVA的JNI技术&#xff0c;通过JAVA自有的方式调用动态链接库&#xff0c;这一篇将继续为大家介绍使用其他方式调用动态链接库。 首先&#xff0c;我们编写一个用于测试的链接库 头文件 print.h #ifdef DLL_IMPLEME…

数组重复次数最多的元素递归_在不使用递归的情况下计算链接列表中元素的出现次数...

数组重复次数最多的元素递归Solution: 解&#xff1a; Input: 输入&#xff1a; A singly linked list whose address of the first node is stored in a pointer, say head and key is the data of which we have to count the number of occurrences. 一个单链表 &#xff…

DshanMCU-R128s2芯片外设支持列表

LCD 显示屏 厂商分辨率型号接口FPS100ask480 x 320Dshan_Display ModuleSPI60 摄像头 Sensor 厂商分辨率型号Size接口FPSGalaxyCoreVGA, 640 x 480GC03081/6.5DVP30GalaxyCoreUXGA, 1616 x 1232GC21451/5DVP13

第6周 搜索与排序

1 查找里程 给你这样一张里程表&#xff0c;如何写一个程序&#xff0c;输入两地的地名&#xff0c;能输出期间的里程&#xff1f; #include <stdio.h> #include <string.h> #define C_LEN 30typedef struct city {char name1[C_LEN];char name2[C_LEN];int distan…

(转) Twisted :第十九部分 改变之前的想法

2019独角兽企业重金招聘Python工程师标准>>> 简介 Twisted是一个正在进展的项目,它的开发者会定期添加新的特性并且扩展旧的特性. 随着Twisted 10.1.0发布,开发者向 Deferred 类添加了一个新的特性—— cancellation ——这正是我们今天要研究的. 异步编程将请求和响…

stl list 删除元素_删除所有出现的元素,并从列表中删除一些特定的元素。 C ++ STL...

stl list 删除元素list.remove()和list.remove_if()函数 (list.remove() and list.remove_if() functions) remove() function is used to remove all occurrences of a given element from the list and function remove_if() is used to remove set of some specific element…

Mac 获取 Brew

2019独角兽企业重金招聘Python工程师标准>>> 终端输入 /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 转载于:https://my.oschina.net/fdstudio/blog/610680

express 项目生成器_用于项目的Express模板生成器(2)| 应用程序结构研究

express 项目生成器Hello! In express template generator for your projects (1), we looked at express generator and how we can start an express application with stressing to build a brand new structure of all required files. 你好&#xff01; 在针对您的项目的E…

简单的block

int multi 7; int (^myBlock)(int) ^(int num){ return num * multi; }; int result myBlock(5); NSLog("结果是&#xff1a;%d",result);//输出结果是&#xff1a; 结果是&#xff1a;35 void (^printBlock)(NSS…

c# 浮点数十六进制字符串_从C#中包含十六进制值的字符串数组中打印整数值...

c# 浮点数十六进制字符串将十六进制字符串数组转换为整数 (Converting array of hexadecimal strings to integers) Let suppose you have some of the strings (i.e. array of strings) containing hexadecimal values like "AA", "ABCD", "ff21&quo…

Linux 服务器中文乱码编码解决

Linux环境的ECS中&#xff0c;若出现如下中文显示为乱码的情况。 一般原因如下: 1. 未安装中文语言包 2. 未设置正确的默认语言 3. SSH 终端未正确配置 本文以Centos 6.5为例&#xff0c;演示如何解决中文乱码问题。 1. 使用 locale -a |grep zh_CN查看系统是否已经安装…

Python | 如何强制除法运算为浮点数? 除数一直舍入为0?

Until the python version 2, the division of two integers was always being rounded down to 0. 在python版本2之前&#xff0c; 两个整数的除法总是四舍五入为0 。 Consider the below example, being executed in python version 2.7, 考虑下面的示例&#xff0c;该示例在…

Python程序输入一个字符串并查找总数的大写和小写字母

Given a string str1 and we have to count the total numbers of uppercase and lowercase letters. 给定字符串str1 &#xff0c;我们必须计算大写和小写字母的总数。 Example: 例&#xff1a; Input: "Hello World!"Output:Uppercase letters: 2Lowercase lette…

Android(Xamarin)之旅(三)

原文:Android&#xff08;Xamarin&#xff09;之旅&#xff08;三&#xff09;前面两篇说到了Xamarin的安装和一些简单的控件&#xff0c;今天来说说一些对话框和提示信息&#xff0c;以及简单的布局元素。 一、对话框和提示信息 一、对话框 我们首先从简单的对话框开始。 1、普…

java中为按钮添加图片_我们可以在Java接口中为成员定义私有和受保护的修饰符吗?...

java中为按钮添加图片No, it is not possible to define private and protected modifiers for the members in interfaces in Java. 不可以&#xff0c;无法为Java接口中的成员定义私有修饰符和受保护的修饰符。 As we know that, the members defined in interfaces are imp…

android Monkey 测试技巧

MonkeyTest 测试流程1、常用的命令参数说明&#xff1a;-sseed值&#xff0c;设置这个参数的主要作用是程序员可以重复执行这个命令&#xff0c;seed值相同则monkey测试序列也大致一样。-p 指定要测试的包&#xff0c;参数跟的是apk的package id--pct-touch 调整触摸…

十六进制数制到二进制,八进制和十进制数制的转换

Prerequisite: Number systems 先决条件&#xff1a; 数字系统 1)将十六进制数制转换为二进制数制 (1) Conversion of Hexadecimal Number System to Binary Number System) To convert hexadecimal numbers into binary numbers, we can use the relationship between hexade…

ldo regula_使用C中的Regula Falsi方法找到复多项式方程的根

ldo regulaRegula Falsi方法 (Regula Falsi method) About the method: 关于方法&#xff1a; We often hear many children and even many adults complaining about the difficulty level that they face while solving complex polynomial equations. It is also difficult…