package Demo0129;
import org.junit.Test;
import java.util.*;
public class CollectionTest {
@Test
public void collectionTest(){
//接口类型的引用指向实现类的对象,形成多态
Collection collection = new ArrayList();
System.out.println(collection);
//向集合中添加元素,该方法的形参要求是Object类型的
boolean b = collection.add("one");//one
System.out.println(collection);
System.out.println("b ="+ b);
collection.add(2);
System.out.println(collection);
collection.add('a');
collection.add(3.14);
collection.add("张辉");
System.out.println(collection);
System.out.println("---------------------------");
//判断是否包含对象
b = collection.contains("one");
System.out.println("b = " + b);
b = collection.contains("two");
System.out.println("b = " + b);
//判断集合是否为空
b = collection.isEmpty();
System.out.println("b = " + b);
System.out.println("============================");
System.out.println("集合中的元素有:" + collection);
b = collection.remove("one");
System.out.println("b = " + b);
System.out.println("集合中的元素有:" + collection);
System.out.println("============================");
//将集合换成数组
Object[] objects = collection.toArray();
//遍历数组中的元素 方式一
for(int i = 0; i < objects.length; i++){
System.out.println(objects[i]);
}
//将数组转换成集合
List objects1 = Arrays.asList(objects);
System.out.println(objects);
//迭代器遍历集合中的元素,方式二
Iterator iterator = objects1.iterator();
while (iterator.hasNext() == true){
Object obj = iterator.next();
System.out.println(obj);
}
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
//遍历集合中的元素 方式三
for (Object p:objects1){
System.out.println(p);
}
}
@Test
public void listTest(){
List list = new ArrayList();
int size =list.size() ;
System.out.println(size);
System.out.println(list);
list.add(0,"one");
list.add(1,2);
list.add(2,3);
list.add(3,3.14);
System.out.println(list);
List list1 = new ArrayList();
list1.add("two");
list1.add(10);
list1.addAll(list);//想集合中添加所有的元素
System.out.println(list1);
System.out.println("-------------------");
//根据下标查看集合中指定位置的元素
Object o = list.get(3);
System.out.println(o);
o = list.set(0,1);//修改指定位置的元素
System.out.println("下标为0的位置修改为:" + o);
System.out.println(list);
o = list.remove(0);//删除指定位置的元素
System.out.println("删除的元素为:" + o);
System.out.println("-------------------------");
System.out.println(list);
List list2 = list.subList(0,2);//获取子list,前闭后开
System.out.println("list的集合:" + list);
System.out.println("子集合的元素" + list2);
list.remove(0);
System.out.println("list集合:" + list);
List list3 = list.subList(0,1);
System.out.println("子集合的元素" + list3);
}
}
@Test
public void queueTest() {
Queue
for (int i = 1; i <= 5; i++) {//将数据11,22,33,44,55依次入列并打印
queue.offer(i * 11);
System.out.println(queue);
}
Integer peek = queue.peek();//查看队首元素并打印
System.out.println(" 队首元素:" + peek);
System.out.println("----------------------");
int len = queue.size();//将数据一次出列并打印
for (int i = 1; i <= len; i++) {
Integer poll = queue.poll();
System.out.println(poll);
}