2020-2-20

Collection 常用功能

  • public boolean add(E e): 把给定的对象添加到当前集合中 。
  • public void clear() :清空集合中所有的元素。
  • public boolean remove(E e): 把给定的对象在当前集合中删除。
  • public boolean contains(E e): 判断当前集合中是否包含给定的对象。
  • public boolean isEmpty(): 判断当前集合是否为空。
  • public int size(): 返回集合中元素的个数。
  • public Object[] toArray(): 把集合中的元素,存储到数组中。
  • Collections.shuffle(pokerBox):打乱功能

tips::在进行集合元素取出时,如果集合中已经没有元素了,还继续使用迭代器的next方法,将会发生java.util.NoSuchElementException没有集合元素的错误。

使用泛型的好处

public class GenericDemo2 {
    public static void main(String[] args) {
        Collection<String> list = new ArrayList<String>();
        list.add("abc");
        list.add("itcast");
        // list.add(5);//当集合明确类型后,存放类型不一致就会编译报错
        // 集合已经明确具体存放的元素类型,那么在使用迭代器的时候,迭代器也同样会知道具体遍历元素类型
        Iterator<String> it = list.iterator();
        while(it.hasNext()){
            String str = it.next();
            //当使用Iterator<String>控制元素类型后,就不需要强转了。获取到的元素直接就是String类型
            System.out.println(str.length());
        }
    }
}

举例自定义泛型类

public class MyGenericClass<T> {
    //没有MVP类型,在这里代表 未知的一种数据类型 未来传递什么就是什么类型
    private T t;
     
    public void setMVP(T t) {
        this.t = t;
    }
     
    public T getT() {
        return t;
    }
}

含有泛型的方法

定义格式:修饰符 <代表泛型的变量> 返回值类型 方法名(参数){ }

public class MyGenericMethod {    
    public <MVP> void show(MVP mvp) {
        System.out.println(mvp.getClass());
    }
    
    public <MVP> MVP show2(MVP mvp) {   
        return mvp;
    }
}

含有泛型的接口

修饰符 interface接口名 <代表泛型的变量> { }

//定义类时确定泛型的类型
public interface MyGenericInterface<E>{
    public abstract void add(E e);
    
    public abstract E getE();  
}

//始终不确定泛型的类型,直到创建对象时,确定泛型的类型
public class MyImp2<E> implements MyGenericInterface<E> {
    @Override
    public void add(E e) {
         // 省略...
    }

    @Override
    public E getE() {
        return null;
    }
}

当使用泛型类或者接口时,传递的数据中,泛型类型不确定,可以通过通配符<?>表示。但是一旦使用泛型的通配符后,只能使用Object类中的共性方法,集合中元素自身方法无法使用。

数据结构

我们将常见的数据 结构:堆栈、队列、数组、链表和红黑树

猜你喜欢

转载自www.cnblogs.com/bestjdg/p/12354833.html