Stack 栈
- 栈是一种先进后出的数据结构
- 比如:浏览器的后退,编译器的撤销等都属于栈的功能
- 在Java 集合中提供有Stack类,这个类是Vector的子类;使用Stack类时候使用的不是Vector类中的方法,并且在使用时不要进行向上转型。因为要操作的方法不是由List定义的,而是由Stack定义的。
- 主要方法:
-
- 入栈:
public E push(E item)
- 入栈:
-
- 出栈:
public synchronized E pop()
- 出栈:
-
- 观察栈顶元素:
public synchronized E peek()
- 观察栈顶元素:
- 出入栈操作
public class Test {
public static void main(String[] args) {
Stack<String> stack = new Stack<>() ;
stack.push("A") ;
stack.push("B") ;
stack.push("C") ;
System.out.println(stack.peek()) ;
System.out.println(stack.pop()) ;
System.out.println(stack.pop()) ;
System.out.println(stack.pop()) ;
// EmptyStackException 空栈异常
System.out.println(stack.pop()) ;
}
}
- 如果栈已经空了,那么再次出栈就会抛出空栈异常
Queue队列
- 队列是一种先进先出的数据结构
- Queue 接口有一个子类LinkedList;
- 按照队列取出内容:
public E poll()
- 队列Queue的poll操作
public class Test {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>() ;
queue.add("A") ;
queue.add("B") ;
queue.add("C") ;
System.out.println(queue.peek()) ;
System.out.println(queue.poll()) ;
System.out.println(queue.poll()) ;
System.out.println(queue.poll()) ;
// 取完数据继续poll返回null
System.out.println(queue.poll()) ;
}
}
- 如果队列中已经没有元素,则返回null
Properties属性文件操作
-
java中,有一种属性文件(资源文件)的定义:
*.properties文件
,在这种文件里面其内容的保存形式为“key = value”
; -
通过
ResourceBundle
类读取的时候只能读取内容,要想编辑其内容需要通过Properties
类来完成,这个类是专门做属性处理的,属性信息都是以字符串的形式出现的,在进行属性操作时会使用properties类提供的方法 -
Properties是Hashtable的子类,定义:
public class Properties extends Hashtable<Object,Object>
-
- 设置属性:
public synchronized Object setProperty(String key, String value)
- 设置属性:
-
- 取得属性:
public String getProperty(String key),如果没有指定的key则返回null
- 取得属性:
-
- 取得属性:
public String getProperty(String key, String defaultValue),如果没有指定的key则返回默认值
- 取得属性:
-
属性操作:(找不到相对应的属性时,返回null)
public class Test {
public static void main(String[] args) {
Properties properties = new Properties() ;
properties.setProperty("XA","Xi'An") ;
properties.setProperty("SH","ShangHai") ;
System.out.println(properties.get("XA")) ;
System.out.println(properties.get("sh")) ;
}
}
-
在Properties类中提供有IO支持的方法:
-
- 保存属性:
public void store(OutputStream out, String comments) throws IOException
- 保存属性:
-
- 读取属性:
public synchronized void load(InputStream inStream) throws IOException
- 读取属性:
-
将属性输出到文件
public class Test {
public static void main(String[] args) throws IOException {
Properties properties = new Properties() ;
properties.setProperty("xa","Xi'An") ;
properties.setProperty("sh","ShangHai") ;
File file = new File("C:\\Users\\Administrator\\Desktop\\test.properties") ;
properties.store(new FileOutputStream(file),"testProperties") ;
}
}
- 通过属性文件读取内容
Properties properties = new Properties() ;
File file = new File("C:\\Users\\Administrator\\Desktop\\test.properties") ;
properties.load(new FileInputStream(file)) ;
System.out.println(properties.getProperty("xa")) ;
Collections工具类
- Collections是一个集合操作的工具类,包含有集合反转、排序等操作