collection集合,list
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");//[]
System.out.println("b = " + b);
collection.add('a');
collection.add('b');//[one, a, b]
System.out.println(collection);
//判断是否包含对象
b = collection.contains("two");
System.out.println("b = " + b);
b = collection.contains("one");
System.out.println("b = " + b);
//判断是否为空
b = collection.isEmpty();
System.out.println("b = " + b);
System.out.println("------");
//删除
b = collection.remove("one");
System.out.println("b = " + b);
//将集合转化成数组
Object[] objects = collection.toArray();
//遍历数组中的元素
for (int i = 0; i < objects.length; i++) {
System.out.print(objects[i] + " ");
}
System.out.println();
//将数组转化成集合
List objects1 = Arrays.asList(objects);
System.out.println(objects1);
System.out.println("-------");
//迭代器只能遍历collection集合,遍历方式二
Iterator it = objects1.iterator();
while (it.hasNext() == true){
Object obj = it.next();
System.out.println(obj);
System.out.println("----");
}
//遍历方式三,foreach
for(Object o : objects1){
System.out.println(o);
}
}
@Test
public void listTest(){
List list = new ArrayList();
int size = list.size();
System.out.println(size);//0
System.out.println(list);//[]
//添加元素
list.add(0,5);
list.add(1,4);
list.add(2,3);
System.out.println(list);
List list1 = new ArrayList();
list1.add("two");
list1.add(10);
list1.addAll(list1);
System.out.println(list1);
//跟据下标查
list1.get(3);
//跟据下标改
list1.set(3,5);
//同时删除list和list1里的下标为1的元素,因为两个表地址相同
list1.remove(1);
System.out.println(list1);
//获取子列表
List list2 = list.subList(0,2);
System.out.println(list2);
}
}
泛型
@Test
public void collectionTest1(){
Collection<String> collection = new ArrayList<>();
collection.add("AA");
collection.add("BB");
collection.add("CC");
collection.add("DD");
System.out.println(collection);
}
Stack
import java.util.Stack;
public class StackDemo {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
for (int i = 1 ;i <= 5;i++){
stack.push(i*11);
}
System.out.println(stack);
//栈顶元素
System.out.println("栈顶元素: " + stack.peek());
//出栈
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}