Fork me on GitHub

【JAVA】几个collection框架

  • Arrays
public static void main(String[] args) {
     String[] s = {"aa","bb","cc"};
        List<String> strlist = Arrays.asList(s);
        for(String str:strlist){
            System.out.println(str);
        }
        System.out.println("------------------------");


        //binarySearch,注意二分查找要求数组有序
        int[] nums1 = {2,4,6,8,10};
        Arrays.binarySearch(nums1, 1);//返回-1
        Arrays.binarySearch(nums1, 8);//返回3
        
        //copyOf,截取or用0填充,该拷贝不影响原来的数组
        int[] nums2 = Arrays.copyOf(nums1, 3);
        
        //copyOfRange,一定范围内截取
        int[] nums3 = Arrays.copyOfRange(nums1, 2, 10);
        
        //fill,填充+范围填充
        Arrays.fill(nums3, 0);
        Arrays.fill(nums3, 0, 4, 0);
        
        //sort,排序
        int[] nums4 = {2,4,10,8,6};
        Arrays.sort(nums4);
    }
  • HashMap<K,V>
public static void main(String[] args) {
        HashMap map=new HashMap(); 
        map.put("a", "aaa");    
        map.put("d", "ddd");   
        map.remove("d", "ddd");   
        map.get("a");//aaa
        map.containsKey("a");//true
        map.keySet();//返回一个set<k>
        Iterator iterator = map.keySet().iterator();                
        while (iterator.hasNext()) {    
         Object keys = iterator.next();    
         System.out.println(map.get(keys));    
        }      
    }
  • LinkedList<E>
public static void main(String[] args) {
        LinkedList<Integer> linkedList = new LinkedList<>();
        linkedList.add(1);
        linkedList.add(2);
        linkedList.add(3);//插在队尾
        linkedList.add(0, 4);//插在0号
        linkedList.contains(1);//true
        
        //要用 LinkedList<Integer> linkedList 不能用 List<Integer> linkedList
        linkedList.element();
        linkedList.get(1);
        linkedList.getFirst();
        linkedList.getLast();
        linkedList.peek();
        linkedList.peekFirst();
        linkedList.peekLast();//获取不移出
        linkedList.poll();
        linkedList.pollFirst();
        linkedList.pollLast();
        linkedList.pop();
        linkedList.push(1);
        linkedList.remove();//获取并移出此列表的头
        //linkedList.remove(1);//移除
        linkedList.set(1, 777);//设置元素
        
        LinkedList<Integer> l = new LinkedList<>();
        l.add(3);
        l.add(2);
        l.add(1);
        l.remove((1));//移除了第[1]个元素 2
        
        LinkedList<Integer> l2 = new LinkedList<>();
        l2.add(3);
        l2.add(2);
        l2.add(1);
        l2.remove(new Integer(1));//移除了元素1,[只移除首次出现的]        
    }
  • //TODO:
posted @ 2018-12-05 23:23  UlyssesCat  阅读(166)  评论(0编辑  收藏  举报