zoukankan      html  css  js  c++  java
  • java学习笔记③JAVA核心API编程-01集合框架和泛型

     

    01 集合框架和泛型

    ArrayList方法—add/ size/ get/ set/ contains/ indexOf / remove(Object obj)/ remove(int index)

    LinkedList方法— addFirst / addLast / removeFirst / removeLast / getFirst / getLast

    HashSet方法—add / clear / size / isEmpty / contains / remove 没有get(index)方法

    HashSet是非线程安全的

    HashMap方法—put / remove/ get / containsKey / containsValue / isEmpty / clear / size 

                              Set keySet() / Collection values()

    ArrayList遍历元素和随机访问元素的效率更高

    LinkedList插入删除元素的效率高

    set存放唯一值

    String类重写了 equals()和hashCode()方法,所以此时认为str1和str3是相等的

    如果在Student类中同时重写equals()和hashCode()方法,也会认为是相等的!

    例如:

    遍历map:Iterator、增强for循环、键值对(keySet取所有key后对set进行普通for循环)

    Iterator<String> iterator = map.keySet().iterator();

    while (iterator.hasNext()) {

      String key = iterator.next();

      System.out.println(key + " :" + map.get(key));

    }

     泛型:

    ArrayList list = new ArrayList();

    list.add("hello");

    Object obj = list.get(0);

    String hello = (String)list.get(0);

    会将插入的数据都变成Object类型,读取时需要强制转换类型

     

     泛型类、泛型方法、泛型接口

    public interface TestInterface<T> {
      public T getName();
     
     public class Student<T> implements TestInterface<T>{

      private T name;
      public Student(T name){
        this.name = name;
      }
      public void setName(T name){
        this.name = name;
      }

      @Override
      public T getName() {
        return name;
      }

      public static void main(String[] args){
        Student<String> st =  new Student<String>("毛毛");
        System.out.println(st.getName());

        News news = new News("1","title1","orange");
        TestInterface<News> news1 = new Student<News>(news);
        System.out.println(news1.getName());
      }
    }
     

    The type parameter String is hiding the type String 提示警告原因:

    JAVA 为什么要用integer定义泛型而不是int?

    因为:泛型需要是对象Object,int是基本数据类型

  • 相关阅读:
    吴恩达机器学习课程笔记章节二单变量线性回归
    cs224n第六讲依存分析
    吴恩达机器学习课程笔记章节一绪论
    cs224n第二讲词向量表示:word2vec
    cs224n第一讲深度自然语言处理
    DIY的.net正则表达式工具
    不写一行代码,利用常用工具和软件批量下载URL资源
    WEB页面采集器编写经验之一:静态页面采集器
    大规模IP地址黑名单高性能查询实现
    安卓开发入门与面试题01(潭州安卓开发入门教程)
  • 原文地址:https://www.cnblogs.com/givemeanorange/p/10387973.html
Copyright © 2011-2022 走看看