• 类集框架(一)


    一、类集接口

    类集提供了以下几种接口:

    ·单值操作:Collection、List、Set

    |—List和Set是Collection接口的子接口,List允许重复,Set不允许重复

    ·一对值的操作接口:Map

    ·排序的操作接口:SortedMap、SortedSet

    ·输出接口:Iterator、ListIterator、Enumeration

    ·队列:Queue

    所有的类集都保存在java.util包中。

    二、Collection接口

    Collection使用了泛型技术,这样做的目的保证了操作内容的安全性。基本上在现在的开发中很少使用Collection接口,而使用其子接口Set和list接口。

    三、List接口

    List接口扩充了Collection的很多方法

    四、Set接口

    1、Set接口有以下两个子类最为常用:

    ·TreeSet:有序存放

    ·HashSet:散列存放

    2、HashSet存放:

    import java.util.HashSet;

    import java.util.Set;

    public class SetDemo {

       public static void main(String[] args) {

         // TODO Auto-generated method stub

         Set<String> s=new HashSet<String>();

         s.add("guoxu");

         s.add("guoxuf");

         System.out.println(s);

       }

    }

    3、TreeSet:

    import java.util.TreeSet;

    import java.util.Set;

    public class SetDemo {

       public static void main(String[] args) {    Set<String> s=new TreeSet<String>();

         s.add("cuoxu");

         s.add("auoxuf");

         System.out.println(s);

       }

    }

    4、关于排序的说明:

    如果要使用自定义的类,并且实现排序,则该类必须继承Comparable接口,并且覆写copareTo方法。

    示例代码如下:

    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;

       }

       public String toString(){

         return name+"-"+age;

       }

       public int compareTo(Person p) {

         if(this.age>p.age){

            return 1;

         }else if(this.age<p.age){

            return -1;

         }else{

            return this.name.compareTo(p.name);

         }

       }

    }

    public class SortedDemo {

       public static void main(String[] args) {

         Set<Person> p=new TreeSet<Person>();

         p.add(new Person("guoxu",25));

         p.add(new Person("cuoxu",27));

         p.add(new Person("auoxu",26));

         p.add(new Person("fuoxu",28));

         System.out.println(p);

       }

    }

  • 相关阅读:
    集合
    字典
    元组
    列表
    数字类型和字符串类型
    Python 数据类型
    jq的一点点
    常用到jq的ajax
    上传
    下载
  • 原文地址:https://www.cnblogs.com/itfenqing/p/4429554.html
Copyright © 2020-2023  润新知