[Java]collection类集中的Set接口
来源:互联网 发布:linux连接数据库命令 编辑:程序博客网 时间:2024/04/30 09:24
Set集合接口有两个子类。1,散列存放子类 HashSet : Set<数据类型> set=new HashSet<数据类型>();
2, TreeSet : Set<数据类型> set=new TreeSet<数据类型>();
具体实现方法;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class Setcollection {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Set<String> set=new HashSet<String>();
Set<String> set=new TreeSet<String>();
set.add("hello");
set.add("hello");
set.add("ado");
set.add("vvv");
System.out.println(set);
}
}
但是对于TreeSet需要注意的是在使用自定义类时,如果想要正常使用TreeSet ,那么一定要在此类上实现java.lang.comparable接口 以区分大小。也就是说,普通的类要实现排序,必须实现Comparable接口,并重写CompareTo()方法。 此时要覆写CompareTo()方法,复写方法时必须注意到所以的属性都必须进行比较,否则就会出现部分属性相同也被认为是同一对象的形式,此时就不会显示出来。具体的范例如下:
import java.util.Set;
import java.util.TreeSet;
class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "姓名:"+name+",年龄"+age+"\t";
}
public int compareTo(Person o){
// 先按age排序
if(this.age>o.age){
return -1;
}
if(this.age<o.age){
return 1;
}
//String也实现了Comparable接口
return this.name.compareTo(o.name);
}
}
public class SetCollectionPerson {
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<Person> set=new TreeSet<Person>();
set.add(new Person("zhangsan",12));
set.add(new Person("xiaoxie",3));
set.add(new Person("haha",23));
set.add(new Person("ha",23));
set.add(new Person("ha",23));
System.out.println(set);
}
}
- [Java]collection类集中的Set接口
- java类集中的SortedSet接口
- java中的collection接口及其set
- JAVA Collection接口、 Set相关知识
- java 集合 Collection接口 List 和Set
- Java-Collection六类接口[Collection,Set,List,Map,Iterator,Comparable]
- Java容器类Collection、List、ArrayList、Vector及map、HashTable、HashMap区别 Collection是List和Set两个接口的基接口
- java中集合类中Collection接口中的Set接口的常用方法熟悉
- Java Collection中的Set类
- 13. Java类集 Part 1(类集、Collection接口、List接口、Set接口、SortedSet接口、集合的输出) ----- 学习笔记
- Java collection接口中list,set,map的区别及用法
- java集合(Collection接口下的 List、Set 深入理解)
- Java Collection接口的总结
- Java Collection接口的总结
- JAVA集合 Set(集)、List(列表)、Map(映射)、Collection(接口)
- Java集合框架官方教程(1):Collection/Set/List接口
- iOS的集中collection布局
- Java基础-Collection之Set的实现
- hadoop eclipse windows
- UVA_725: Division
- POJ 2032 搜索 (IDA*) 或 DLX
- android系统开发中log的使用方法
- Python Linux下安装python 软件包
- [Java]collection类集中的Set接口
- Java Web 中使用ffmpeg实现视频转码、视频截图
- HDU_2448_Mining Station on the Sea(最短路 + 最小费用流)
- POJ 1836 Alignment (简单DP)
- VTK鼠标选点
- Intellij Idea 将java项目打包成jar
- UESTC 92 Journey(LCA或树剖)
- 快速排序
- POJ2777 Count Color 线段树区间更新