Set接口

来源:互联网 发布:windows mysql 客户端 编辑:程序博客网 时间:2024/05/20 12:23

Set接口也是Collection接口的子接口,但是与Collection或List接口不同的是,Set接口不能加入重复的元素。
定义格式

public interface Set<E>extends Collection<E>        

Set接口主要方法与Collection接口一致
Set接口的实例无法像List接口一样双向输出
Set接口的常用子类
散列存放:HashSet
有序存放:TreeSet

import java.util.HashSet ;import java.util.Set ;public class HashSetDemo01{    public static void main(String[] args)    {        Set<String> allSet = new HashSet<String>() ;        allSet.add("A") ;   //增加内容 此方法由Collection继承来        allSet.add("B") ;   //增加内容 此方法由Collection继承来        allSet.add("C") ;   //增加内容 此方法由Collection继承来        allSet.add("C") ;   //增加重复内容 此方法由Collection继承来        allSet.add("D") ;   //增加内容 此方法由Collection继承来        allSet.add("E") ;   //增加内容 此方法由Collection继承来        System.out.println("输出内容:"+allSet) ;    }}

HashSet:使用的是散列的方式存放内容,本身没顺序,而List接口的内容插入的顺序就是保存顺序

TreeSet也是Set接口子类 有序存放

import java.util.TreeSet ;import java.util.Set ;public class TreeSetDemo01{    public static void main(String[] args)    {        Set<String> allSet = new TreeSet<String>() ;        allSet.add("A") ;   //增加内容 此方法由Collection继承来        allSet.add("B") ;   //增加内容 此方法由Collection继承来        allSet.add("C") ;   //增加内容 此方法由Collection继承来        allSet.add("C") ;   //增加重复内容 此方法由Collection继承来        allSet.add("D") ;   //增加内容 此方法由Collection继承来        allSet.add("E") ;   //增加内容 此方法由Collection继承来        System.out.println("输出内容:"+allSet) ;    }}

一个对象数组要实现排序,必须使用Comparable接口完成,对于TreeSet也一样,如果要使用TreeSet进行排序,则对象所在的类也要实现Comparable接口。

import java.util.Set ;      //导入Set接口import java.util.TreeSet ;  //导入TreeSet类class Person implements Comparable<Person>      //定义Person类{    private String name ;       private int age ;    public Person(String name,int age)    {        this.name = name ;        this.age = age ;    }    public String toString()    {        return "姓名:"+this.name+";年龄:"+this.age ;    }    public int compareTo(Person per)    {        if(this.age>per.age)        {            return 1 ;        }        else if (this.age<per.age)        {            return -1 ;        }        else        {            return 0 ;        }    }}public class TreeSetDemo02{    public static void main(String[] args)    {        Set<Person> allSet = new TreeSet<Person>() ; //实例化TreeSet对象        allSet.add(new Person("张三",20)) ; //向集合中插入多个Person对象        allSet.add(new Person("李四",21)) ; //向集合中出入Person对象        allSet.add(new Person("王五",12)) ; //向集合中插入Person对象        allSet.add(new Person("王五",12)) ; //向集合中插入Person对象        allSet.add(new Person("王五",23)) ; //向集合中插入Person对象        allSet.add(new Person("小六",12)) ; //向集合中插入Person对象        System.out.println("\n"+allSet) ;    }}
0 0
原创粉丝点击