Java集合框架【二容器(Collection)[Vector容器类]】
文章目录
- 三 Vector容器类
- 3.5 Vector容器类
- 3.5.1 Vector的使用
- 3.5.2 Stack容器
- 3.5.3.1 Stack容器介绍
- 3.5.3.2 操作栈方法
- Stack的使用案例
三 Vector容器类
3.5 Vector容器类
- Vector底层是用数组实现的,相关的方法都加了同步检查,因此“线程安全,效率低”比如,indexOf方法就增加了synchronized同步标记。
3.5.1 Vector的使用
Vector的使用与ArrayList是相同的,因为他们都实现了List接口,对List接口中的抽象方法做了具体实现。
/**
- @author 缘友一世
date 2022/11/18-14:10
*/
public class VectorTest {public static void main(String[] args) {
Vector<String> v = new Vector<>();
v.add("aaa");
v.add("bbb");
v.add("ccc");
for(int i=0;i<v.size();i++) {
System.out.print(v.get(i)+" ");
}
}
}
3.5.2 Stack容器
3.5.3.1 Stack容器介绍
- Stack栈容器,是Vector的一个子类,它实现了一个标准的后进先出(LIFO:LastinFristOut)的栈。
- Stack特点是:后进先出。它通过5个操作方法对Vector进行扩展,允许将向量视为堆栈。
3.5.3.2 操作栈方法
/**
* @author 缘友一世
* date 2022/11/18-14:22
*/
public class StackTest {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("521");
stack.push("1314");
stack.push("999");
System.out.println(stack.empty());
System.out.println(stack.peek());
System.out.println(stack.search("521"));
for(String s: stack) {
System.out.println(s);
}
}
}
Stack的使用案例
/**
* @author 缘友一世
* date 2022/11/18-14:29
*/
public class StackApplication {
public static void main(String[] args) {
String str="...{...[...(....)...]...}..(....)..[...]...";
Stack<String> stack = new Stack<>();
//假设修正法
boolean flag=true;//假设是匹配的
//拆分字符和获取字符
for(int i=0;i<str.length();i++) {
char c=str.charAt(i);
if(c=='{') {
stack.push("}");
}else if(c=='[') {
stack.push("]");
}else if(c=='(') {
stack.push(")");
}
if(c=='}'||c==']'||c==')') {
if(stack.empty()) {
//如果是空栈就进行修正
flag=false;
break;
}
String x=stack.pop();
//如出栈的字符与遇到的字符不同,就进行修正
if(x.charAt(0)!=c) {
flag=false;
break;
}
}
}
//如果最终匹配所有字符之后,栈不为空,说明字符不对称
if(!stack.empty()) {
flag=false;
}
System.out.println(flag);
}
}
还没有评论,来说两句吧...