• Java的集合


    1.  HashMap排序题,上机题。

    已知HashMaptegerUser>  UsernameStringageint请写法实HashMap 能,该方接收 HashMap<IntegerUser>,返回类 HashMap<IntegerUser>,要HashMapUseragekey=value不得 

    注意要做出这题必须对合的体系构非常的HashMap 本身不可排的,但该道题HashMap我们就得API有这MapLinkedHashMapMap是他HashMapLinkedHashMap<Integer,User>

    即可父类 

    但凡们应JDKAPIJDKAPI法我

    该去是首Collections类。 

    1. public class HashMapTest { 

    2.   public static void main(String[] args) { 

    3.   HashMap users = new HashMap<>(); 

    4.   users.put(1, new User("张三", 25));

    5.   users.put(3, new User("李四", 22));

    6.   users.put(2, new User("王五", 28));

    7.   System.out.println(users); 

    8.   HashMap sortHashMap = sortHashMap(users); 

    9.   System.out.println(sortHashMap); 

    10.   /**

    11.    * 控制台输出内 

    12.    * {1=User [name=张三, age=25], 2=User [name=王五, age=28], 3=User [name=李四, age=22]}

    13.   {2=User [name=, age=28], 1=User [name=张三, age=25], 3=User [name=李四, age=22]}

    14.    */ 

    15.  }

    16.  

    17.  public static HashMap sortHashMap(HashMap map) { 

    18.   // 首先拿map的键值对集 

    19.   Set> entrySet = map.entrySet(); 

    20.  

    21.   // set集合转List集合,为什么,为了使用工具类的排序方法 

    22.   List> list = new ArrayList>(entrySet); 

    23.   // 使Collections集合工具类list进行排序,排序规则使用匿名内部类来实 

    24.   Collections.sort(list, new Comparator>() {

    25.  

    26.   @Override

    27.   public int compare(Entry o1, Entry o2) { 

    28.   //按照要求根Userage的倒序进行排 

    29.   return o2.getValue().getAge()-o1.getValue().getAge();

    30.   }

    31.   });

    32.   //创建一个新的有序HashMap子类的集合 

    33.   LinkedHashMap linkedHashMap = new LinkedHashMap(); 

    34.   //List中的数据存储LinkedHashMap 

    35.   for(Entry entry : list){ 

    36.   linkedHashMap.put(entry.getKey(), entry.getValue()); 

    37.   }

    38.   //返回结果 

    39.   return linkedHashMap; 

    40.  }

    41. }

    42.  

    2.  集合的全性问题 

    ArrayListHashSetHashMap线安全的吗线程安办? 

    我们的源就看线不安又说

    过来没第了。 

    集合 Vector  HashTable 线程安源码其实各自法添加上

    synchronized关键 

    Collections供了API上面3变为安全的。 

    1. //  Collections.synchronizedCollection(c) 

    2. //  Collections.synchronizedList(list) 

    3. //  Collections.synchronizedMap(m) 

    4. //  Collections.synchronizedSet(s) 

    上面几个函数都有对应的返回值类型,传入什么类型返回什么类型。打开源码其实实现原理非常简单,就是

    合的synchronized关键 

    3.  ArrayList部用么实现2015-11-24 

    (回只回ArrayList何实因为

    组在定的ArrayList加对些数?) 

    ArrayListObject[]实现们分别分ArrayList addremoveclear方法实现

    原理 

    构造 

    1 

    /**
     * Constructs a new {@code ArrayList} instance with zero initial capacity.

     */ 

     public ArrayList() {

     array = EmptyArray.OBJECT; 

    }

    arrayObject[]new空参构造EmptyArray.OBJECT属性EmptyArray

    仅是类源下: 

    public final class EmptyArray { 

     private EmptyArray() {}

     public static final boolean[] BOOLEAN = new boolean[0]; 

     public static final byte[] BYTE = new byte[0]; 

     public static final char[] CHAR = new char[0]; 

     public static final double[] DOUBLE = new double[0]; 

     public static final int[] INT = new int[0];

     public static final Class[] CLASS = new Class[0]; 

     public static final Object[] OBJECT = new Object[0]; 

     public static final String[] STRING = new String[0]; 
     public static final Throwable[] THROWABLE = new Throwable[0]; 
     public static final StackTraceElement[] STACK_TRACE_ELEMENT = new StackTraceElement[0]; }

    也就当我new ArrayList系统使了一new Object[0] 

    2带参1 

     /** 
     * Constructs a new instance of {@code ArrayList} with the specified  * initial capacity.

     * 

     * @param capacity 

     *            the initial capacity of this {@code ArrayList}.

     */ 

     public ArrayList(int capacity) { 

     if (capacity < 0) {
     throw new IllegalArgumentException("capacity < 0: " + capacity); 

     } 
     array = (capacity == 0 ? EmptyArray.OBJECT : new Object[capacity]); }

    该构int0抛出0

    使用0该值 

    32 

    /**
     * Constructs a new instance of {@code ArrayList} containing the elements of  * the specified collection.

     * 

     * @param collection

     *            the collection of elements to add.

     */ 

     public ArrayList(Collection collection) { 

     if (collection == null) { 

     throw new NullPointerException("collection == null");

     } 

     Object[] a = collection.toArray(); 

     if (a.getClass() != Object[].class) { 

     Object[] newArray = new Object[a.length]; 

     System.arraycopy(a, 0, newArray, 0, a.length); 

     a = newArray;

     } 

     array = a; 

     size = a.length; 

     } 

    如果传入了一Collectionnullnull出空指针

    集合转换为数a将该数组arraysize

    里面a.getClass是否Object[].class其实也暂加了判断

    toArrayCollection接口的子listtoArraySettoArray

    返回的都Object[] 

    这里实在Java时候作者的很知道他为何ArrayList  array的成方法使时候都会

    新在array使用人可array

    array大家使array然后使并不

    也许代码已。 

    add 

    add里只 

     /** 
     * Adds the specified object at the end of this {@code ArrayList}.

     * 

     * @param object 

     *            the object to add.

     * @return always true

     */ 

     @Override public boolean add(E object) { 

     Object[] a = array;

     int s = size; 

     if (s == a.length) {

     Object[] newArray = new Object[s + 

     (s < (MIN_CAPACITY_INCREMENT / 2) ? 

     MIN_CAPACITY_INCREMENT : s >> 1)];

     System.arraycopy(a, 0, newArray, 0, s); 

     array = a = newArray; 

     } 

     a[s] = object; 

     size = s + 1; 

     modCount++; 

     return true; 

     } 

    1首先array值给asizes 

    2判断s否等于数集合的长满了重新

    分配新数组了 ,重新分配数组的时候需要计算新分配内存的空间大小,如果当前的长度

    MIN_CAPACITY_INCREMENT/21226就是如果612

    长度6s的一半长元运s >> 1

    s1s=s/2最高算。 

    3将新添加object为数a[s] 

    4修改sizes+1 

    5modCotun++,量是父类集合合修在用

    器迭改异是否 

    6return true回值意义直返true,除异常 

    remove方法 

    remove,我removeint index 

     /** 
     * Removes the object at the specified location from this list. 

     * 

     * @param index 

     *            the index of the object to remove.

     * @return the removed object.

     * @throws IndexOutOfBoundsException
     *             when {@code location < 0 || location >= size()}  */ 

     @Override public E remove(int index) { 

     Object[] a = array;

     int s = size; 

     if (index >= s) {

     throwIndexOutOfBoundsException(index, s); 

     } 

     @SuppressWarnings("unchecked")  

     E result = (E) a[index]; 

     System.arraycopy(a, index + 1, a, index, --s - index);

     a[s] = null;  // Prevent memory leak 

     size = s; 

     modCount++; 

     return result; 

     } 

    1先将arraysizeas 

    2判断index等于了则 

    3获取indexresult象作为方 

    4Systemarraycopy下图所示 

    5接下个元前移动了一位将集合最

    个元null就可露。 

    6重新arraysize 

    7记录 

    8返回再看 

    clear 

     /** 
     * Removes all elements from this {@code ArrayList}, leaving it empty.

     * 

     * @see #isEmpty 

     * @see #size 

     */ 

     @Override public void clear() { 

     if (size != 0) { 

     Arrays.fill(array, 0, size, null); 

     size = 0; 

     modCount++; 

     } 

     } 

    如果0则将nullsize0即可让修改记1 

    4.  并发集和普通集合如何别?(2015-11-24 

    并发ConcurrentHashMapConcurrentLinkedQueueConcurrentLinkedDeque并发

     

    java.util.concurrent

       

    jdk1.5

              

    Doug

    Lea

    完成 

    java、同步(线全)的并发性能最高线程安全性和线安全synchronized而且对并就更低复杂线程时的 

    参考 
      ConcurrentHashMap 是线 HashMap 的实同样 initialCapacity  loadFactor 性,不过一个 concurrencyLevel 认值 160.75  16使术,SegmentSegment存放Entity[]hash将数锁中 

    putsynchronizedkey.hashcodehashkeyhash值。hash算法map也不hash算并Segment对象(ReentrantLock),接着调用Segmentput操作 

    ConcurrentHashMap  concurrencyLevel 分出多个 Segment  key-value 从而免每put数组佳情可允16线程并发减少 

    get(key) 

      key.hashCode  hash 其值 Segment  get 方法完成前操作。而 Segment  get 操作 hash 对象小减 1 值进行按上对HashEntry中,大小对应位置HashEntry生不性,ConcurrentHashMap是如 

      put 发生,由 HashEntry 象数 volatile 类型的,HashEntry发生改变的对小。 

     取到 HashEntry 象后,怎么保证它 next 属性上的对象不ConcurrentHashMap用了HashEntryhashkeynextfinal也就意味HashEntry到基next属性获取HashEntry对象其基next构建化的 

      ConcurrentHashMap 采用分为 16 储, 16 有各自不的锁Segment用于 put  remove 象的,基 volatile  HashEntry 不变性实的不使ConcurrentHashMap能够保持其是除频Map而言法也是对Java模型的体 

    5.  List的三子类特点

    ArrayList ,底层询快,删慢。 

    LinkedList 表型的,, 

    voctor  底层 线安全,,慢。 

    6.  ListMapSet的区别2017-11-22-wzz 

    6.1  结构特 

    List Set据的Map和值合;List的数据是有顺,并且允Map 的数键是是可Set 存储据是无序元素hashcode置是Sethashcode

    进行以位置是置不是用所以对于set素还序的 

    6.2  实现类 

    ListLinkedList实现每一个元的同存储链表ArrayList非线全的便于,但不便于Vector基于线的, 

    Map 类(HashMap hash  Map 线程安支持 null  nullHashTable线nullnullLinkedHashMapHashMap个子存了记录SortMapTreeMap把它序,序) 

    Set 现类HashSet HashMap 集合有重使时需重写 equals() hashCode()方法;LinkedHashSet继承HashSetLinkedHashMap进行层使用的LinkedHashMp)。 

    6.3  区别 

    List 中对象照索位置排序,有重复,允许按对象在集的索引位检索对象例如list.get(i)集合中的元素Map个元可以重复对象可Set对象它的对象的方TreeSet也可Java.util.Comparator<Type>来自序方式 

    7.  HashMap HashTable什么?

    HashMap线安全的,HashMap,Map接口,将键对象,许键重复,

    允许空值;线程安全,HashMap效率HashTable一些. 

    HashTable 线一个,nullkeyValue;
    HashTable  sychronize,多个线访己为, HashMap 线访问时候需现同步; 

    8.  数组和表分别比较适合于什景,为么?

    8.1  数组和链表 

    在计算机中要对给定的数据集进行若干处理,首要任务是把数据集的一部分(当数据量非常大时,可能只能部分一存中到内中的 

    例如 S{123456} S 中元据存将内存中数据 

    当内存空间中有足够大的连续空间时,可以把数据连续的存放在内存中,各种编程语言中的数组一般都是按种方式存也可外), 1b);内存中些离用空间连续据就非了,这时式是把离的一1c所示做当然也可以,但是这种情况因为可能要移动别人的数据,所以会存在一些困难,移动的过中也有可能会把一些人的重外一存储方式分开连续,如d能把数据的存数据这样只知道内存间的址就相扣把数集整在一了。C/C++的链就是种存储 

    由上可知,内存中的存储形式可以分为连续存储和离散存储两种。因此,数据的物理存储结构就有连续存储离散存我们 

    8.2  数组和链表区别 

    数组续存储的优点因为数据储的地址据的候效率比较高储之块连空间并且在编好它的大小。在运行的时候空间的大小是无法随着你的需要进行增加和减少而改变的,当数据两比较大的时候,有可能会现越界的时掉内数据个数数据  链表是动态申请内存空间,不需要像数组需要提前申请好内存的大小,链表只需在用的时候申请就可以,根需要来动态申请或者删除内存空间,对于数据增加和删除以及插入比数组灵活。还有就是链表中数据在内中可以任意的联数素的 

    8.3  链表和数组使用场景 

    数组场景按序号访容易语言都支构建的线 

    链表线的长;频构建线 

    8.4  跟数组相关面试题 

    组中value 按如出:  1 1  

    3 2  

    8 3  

    2 4  

    int[] arr = {1,4,1,4,2,5,4,5,8,7,8,77,88,5,4,9,6,2,4,1,5}; 

    9.  JavaArrayListLinkedlist

    ArrayListVector使了数ArrayListVector装了比如向数组中添元素定向 

    LinkedList使向链基于ArrayList是两决定了同的 

    LinkedList表项总是3元素内容如图 

    在下个包3个元LinkedList个表JDK,无LikedList是否为空header表项示链表的结尾header驱表便链表中第header便是链表中最后 

    10. List a=new ArrayList()ArrayList a =new ArrayList()的区别 

    List list = new ArrayList();这句了一ArrayList的对溯到ListList对象有些ArrayList 有但 List 有的能再 ArrayList  list=new ArrayList();一对留了ArrayList 所以ArrayList有的者。 

    1List list = new ArrayList(); 

    2ArrayList arrayList = new ArrayList(); 

    3list.trimToSize(); //错误,没有该方法 

    4arrayList.trimToSize();   //ArrayList里有该方法。 

    11. 要对集更新操作时,ArrayListLinkedList合?(2017-2-24) 

    1.ArrayList动态LinkedList构。 

      2.合数于集机访getsetArrayListLinkedListLinkedList要移  

      3.合数于集 add  removeLinedList 比较 ArrayList 移动数据。 

    ArrayList LinkedList 是两一系(references)ArrayList 存储StringInteger ArrayListLinkedList上有什么ArrayList什么又该LinkedList呢? 

    时间 
    首先ArrayList础的使get访中的一个元(random  access),它LinkedListLinkedListget表的一端始检查,LinkedList访的某的方 

    假设好序ArrayListLinkedList

    类型列表查找(binary  search) ArrayList  LinkedList 时的度,

    看下 

    1public class TestList{

    2     public static final int N=50000;    //50000个数 

    3     public static List values;           //查找的集合 

    4      //50000个数value 

    5     static{

    6         Integer vals[]=new Integer[N];

    7         Random r=new Random(); 

    8         for(int i=0,currval=0;i{ 

    9             vals=new Integer(currval); 

    10             currval+=r.nextInt(100)+1; 

    11         }

    12         values=Arrays.asList(vals);

    13     }

    14     //通过二分查找法查 

    15     static long timeList(List lst){

    16         long start=System.currentTimeMillis(); 

    17         for(int i=0;i{ 

    18             int index=Collections.binarySearch(lst, values.get(i));

    19             if(index!=i) 

    20                 System.out.println("***错误***");

    21         }

    22         return System.currentTimeMillis()-start;

    23     }

    24     public static void main(String args[])...{

    25         System.out.println("ArrayList消耗时间"+timeList(new ArrayList(values)));

    26         System.out.println("LinkedList消耗时间"+timeList(new LinkedList(values)));

    27     }

    28}

    得到 

    1. ArrayList消耗时间:15

    2. LinkedList消耗时间:2596

    ,但 ArrayList  LinkedList 种情宜用

    LinkedList使用访(random access) LinkedList 机访问的一个

    Entryreference 时还LinkedList的上素。1000元素LinkedList1000个链接在 Entry每个的一。这样LinkedList的空1000  Entity的相 

    ArrayList使数组 组的容量10.需要如下公式获=(*3)/2+1是说容量会增50% 这就个包元素ArrayList最终浪费ArrayList 果没有的元重新便加新重新将会导致我们  ArrayList将会可以容量还可以trimToSizeArrayList去掉 间。 

    三. 
    ArrayListLinkedList性能各自说来 
    1ArrayList  LinkedList加一是固ArrayList言,主要是项, 组重新进LinkedList这个开Entry 

    2ArrayList间插入或这个会被;而LinkedList中间插入销是的。 

    3LinkedList高效的随访问。 

    4ArrayList主要list结尾LinkedList费则现在它的耗相空间 
    可以一列而不中间,需要访素时,使ArrayList性能列数或删数据,访问元素时,该使LinkedList 

    12. 请用两队列模拟堆栈结

    两个队列是先如下 

    ab 

    1入栈ab为空。例a,b,c,d,e需要aaa,b,c,d,e 

    2出栈aa,b,c,,d,e”。a列依次加Arraylistaa的集

    合取bb 

    1 public static void main(String[] args) {

    2          Queue queue = new LinkedList();  //a  

    3          Queue queue2=new LinkedList();   //b队列 

    4          ArrayListg> a=new ArrayList();     //arrylist集合是中间参数 

    5          //a队列添加元 

    6          queue.offer("a");

    7          queue.offer("b"); 

    8          queue.offer("c"); 

    9          queue.offer("d"); 

    10         queue.offer("e"); 

    11         System.out.print("进栈:");

    12        //a队列依次加list集合之中 

    13         for(String q : queue){ 

    14          a.add(q);

    15           System.out.print(q);

    16         } 

    17        //以倒序的方法取出(a队列依次加list)之中的值,加b对列 

    18         for(int i=a.size()-1;i>=0;i--){

    19          queue2.offer(a.get(i));

    20         } 

    21        //打印出栈队 

    22         System.out.println(""); 

    23         System.out.print("出栈:");

    24         for(String q : queue2){

    25             System.out.print(q); 

    26         } 

    27  } 

    打印先进): 

    进栈:a b c d e

    出栈:e d c b a

    13. CollectionMap的集成

    Collection 

    Map 

    14. Mapkeyvalue可以null

    HashMapkeyvaluenull 

    HahTablekeyvaluenull 

    且两者的key不能重复key同的键值value自动前面value不会错。

    测试 

    1. public class Test {

    2.  

    3.     public static void main(String[] args) {

    4.         Maping> map = new HashMap();//HashMap对象 

    5.         Maping> tableMap = new Hashtable();//HashTable对象 

    6.  

    7.         map.put(null, null);

    8.         System.out.println("hashMap[key][value]均可以null:" + map.get(null));

    9.  

    10.         try { 

    11.             tableMap.put(null, "3");

    12.             System.out.println(tableMap.get(null));

    13.         } catch (Exception e) {

    14.             System.out.println("ERROR】:hashTable[key]不能null");

    15.         } 

    16.  

    17.         try { 

    18.             tableMap.put("3", null);

    19.             System.out.println(tableMap.get("3"));

    20.         } catch (Exception e) {
    21.             System.out.println("ERROR】:hashTable[value]不能null"); 22.         } 

    23.     } 

    24.  

    25. }

    运行 

    hashMap[key][value]null:null

    ERRORhashTable[key]null

    ERRORhashTable[value]null 

  • 相关阅读:
    Hive安装配置 - 内嵌模式
    Memcached:高性能分布式缓存系统的奥秘解锁
    pytorch:dataloader自定义数据集制作
    大二上学期学习计划
    为什么MyBatis是Java数据库持久层的明智选择
    数据分表Mybatis Plus动态表名最优方案的探索
    leetcode 1208.尽可能使字符串相等 滑动窗口
    【软考软件评测师】第十六章 性能测试基础
    请求数据应该放在Created还是Mounted
    面试理论篇三
  • 原文地址:https://blog.csdn.net/2301_77822280/article/details/130919300