zoukankan      html  css  js  c++  java
  • hashSet的底层是数组,其查询效率非常高

    如果偷懒,没有设定equals(),就会造成返回hashCode虽然结果相同,但在程序执行的过程中会多次地调用equals(),从而影响程序执行的效率。

     

    我们要保证相同对象的返回的hashCode一定相同,也要保证不相同的对象的hashCode尽可能不同(因为数组的边界性,hashCode还是可能相同的)。例子:

    public int hashCode(){

     return name.hashcode()+age;

    }

    这个例子保证了相同姓名和年龄的记录返回的hashCode是相同的。

     

    使用hashSet的优点:

    hashSet的底层是数组,其查询效率非常高。而且在增加和删除的时候由于运用的hashCode的比较开确定添加元素的位置,所以不存在元素的偏移,所以效率也非常高。因为hashSet查询和删除和增加元素的效率都非常高。

    但是hashSet增删的高效率是通过花费大量的空间换来的:因为空间越大,取余数相同的情况就越小。HashSet这种算法会建立许多无用的空间。

    使用hashSet接口时要注意,如果发生冲突,就会出现遍历整个数组的情况,这样就使得效率非常的低。

     1 package TomTexts;
     2 
     3 
     4 class Student         //定义Student类
     5 {
     6         String name;    //姓名
     7         int age;        //年龄
     8         public Student(String pname,int page)    //构造函数
     9         {
    10             name=pname;
    11             age=page;
    12         }
    13 }
    14 public class TomTexts_14        //定义主类
    15 {
    16         public static void main(String [] args)
    17         {
    18             Student [] e=new Student[5];     //声明Student对象数组
    19             e[0]=new Student("张三",25);    //调用构造函数,初始化对象元素
    20             e[1]=new Student("李四",30);
    21             e[2]=new Student("王五",35);
    22             e[3]=new Student("刘六",28);
    23             e[4]=new Student("赵七",32);
    24             System.out.println("平均年龄"+getAverage(e));
    25             getAll(e);
    26         }
    27         static int getAverage(Student [] d)        //求平均年龄
    28         {
    29             int sum=0;
    30             for (int i=0;i<d.length;i++)
    31                 sum=sum+d[i].age;
    32             return sum/d.length;
    33         }
    34         static void getAll(Student [] d)        //输出所有信息
    35         {
    36             for (int i=0;i<d.length;i++)
    37                 System.out.println(d[i].name+d[i].age);
    38         }
    39 }
  • 相关阅读:
    input框限制0开头的数字(0除外)
    圆角头像----CSS3特效
    html中div获取焦点,去掉input div等获取焦点时候的边框
    一些常用的html css整理--文本长度截取
    html5本地存储
    div块级元素获取焦点
    Intellij IDEA 搜索文件内容
    web安全漏洞防护
    Intellij IDEA 自动生成 serialVersionUID
    mysql 年龄计算(根据生日)
  • 原文地址:https://www.cnblogs.com/borter/p/9420370.html
Copyright © 2011-2022 走看看