集合,迭代器

2017-05-20  本文已影响0人  云承寒

集合的体系

单列集合

Collection

Collection中的API

public static void demo() {
        Collection<String> collection = new ArrayList();
        collection.add("Demo"); //添加一个元素,类型为Object
        collection.addAll(null); //添加一个Collection集合
        
        collection.clear(); //清空集合
        collection.remove("Demo"); //删除集合中的某个元素
        collection.removeAll(null); //删除一个集合中的所有相同元素
        collection.retainAll(null);//保留交集元素,删除其他元素
        
        collection.isEmpty();//判断集合是不是为空
        collection.contains("Demo");//判断集合是否包含这个元素
        collection.containsAll(null);//判断集合中时候包含指定集合中的所有元素
        
        collection.iterator();//迭代器
        collection.size();//返回集合大小
}

List

List的特点是集合中的元素有序,可重复,可以通过索引来访问集合中的指定元素。

List的有序是指:元素的存入顺序和取出顺序一致,因为List集合中的元素是以线性的顺序存储的。

ArrayList
Vector
LinkedList
List提供的API
public static void demo() {
        ArrayList<String> list = new ArrayList<>();
        list.add(0,"Demo");//将元素插入指定索引处
        list.addAll(1,list);//将集合插入指定索引处

        list.get(0);//获取指定索引处的元素
        list.set(0,"Changed");//修改指定索引处元素数据
        list.remove(1);//删除指定索引出元素

        list.indexOf("Demo");//返回该元素在集合中的位置索引
        list.lastIndexOf("Demo");//返回该元素在集合中最后一次出现的位置索引

        //Linked
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.addFirst("First");
        linkedList.addLast("Last");

        linkedList.removeFirst();
        linkedList.removeLast();

        linkedList.getFirst();
        linkedList.getLast();
    }

Set

Set的特点是集合中的元素无序,不重复。
Set的无序是指:添加元素的顺序与取出元素的顺序不一致。

HashSet
注意细节
public class Run {
    public static void main(String[] args) {
        test();
    }

    public static void test() {

        HashSet<User> hashSet = new HashSet<>();
        hashSet.add(new User(1, "Test1"));
        hashSet.add(new User(1, "Test2"));
        hashSet.add(new User(1, "Test3"));

        System.out.println(hashSet);

    }
}

class User {
    int id;
    String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return id + ":" + name;
    }

    @Override
    public int hashCode() {
        return this.id;
    }

    @Override
    public boolean equals(Object obj) {
        User user = (User) obj;
        return this.id == user.id;
    }
}

TreeSet

内部采用平衡二叉树来存储元素,二叉树结构可以保证TreeSet集合中没有重复的元素,并且可以对其内元素进行排序。

TreeSet注意事项
class Test<T> implements Comparable<T> {

    @Override
    public int compareTo(T o) {

        // 返回负整数,零或正整数,根据此对象是小于,等于还是大于指定对象
        return 0;
    }
}
class Test<T> implements Comparator<T> {

    @Override
    public int compare(T o1, T o2) {
        return 0;
    }
}

Map集合

 public static void demo() {
        Map<String, String> map = new HashMap<>();
        for (int i = 1; i <= 3; i++)
            map.put("Key" + i, "Value" + i);

        map.get("Key1"); //获取数据
        map.containsKey("Key1"); //是否包含这个Key
        map.containsValue("Value1"); //是否包含这个Value

        for (Map.Entry<String, String> item : map.entrySet()) {
            System.out.println(item.getKey() + ":" + item.getValue());
        }
    }

Collections集合工具类

    public static void main(String[] args) throws Exception {

        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.add("Test1");
        linkedList.add("Test3");
        linkedList.add("Test2");
        linkedList.add("Test4");

        //升序排列
        Collections.sort(linkedList);
        //倒序排序
        Collections.reverse(linkedList);
        //随机排序
        Collections.shuffle(linkedList);
        //折半查找
        Collections.binarySearch(linkedList, "Test1");

        //复制集合
        //      Collections.copy(dest, src);

        System.out.println(linkedList);
    }

迭代器

迭代器的作用就是抓取集合的元素。

Iterator
    public static <T> void test(ArrayList<T> list) {

        Iterator<T> iterator = list.iterator();
        
        while (iterator.hasNext()) {
            
//          iterator.remove();
            
            System.out.println(iterator.next());
        }
    }
ListIterator

ListIterator为Iterator的子类

public static <T> void test(ArrayList<T> list) {

        ListIterator<T> listIterator = list.listIterator(list.size());

        // hasPrevious 是否有上一个元素
        while (listIterator.hasPrevious()) {

            // add() 把当前元素插入当前指针指向的位置上
            // listIterator.add();

            // 替换迭代器最后一次返回的元素
            // listIterator.set();

            // previous先将指针上移,再取出元素
            System.err.println(listIterator.previous());

        }
    }
增强for循环

简化迭代器的书写格式(增强for循环的底层还是使用迭代器实现的)。

//格式
for(目标变量类型 变量名:遍历的集合/数组){

}
增强for注意事项
//自定一个类使用增强for循环
class MyList implements Iterable<String>{
    
    Object[] arr = new Object[10];
    
    int index = 0 ; //当前的指针
    
    public void add(Object o){
        arr[index++] = o;  // 1
    }
    
    public int size(){
        return index;
    }

    @Override
    public Iterator<String> iterator() {
        
        
        return new Iterator<String>() {

            int cursor  = 0;

            @Override
            public boolean hasNext() {
                return cursor<index;
            }

            @Override
            public String next() {
                return (String) arr[cursor++];
            }

            @Override
            public void remove() {
                
            }
        };
    }
}
上一篇 下一篇

猜你喜欢

热点阅读