代码摘录尚学堂
Date和DateFormat转换
<span style="font-size:14px;">import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateFormat {
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,属于本月的第W周");
Date d = new Date(12321314323L);
String str = df.format(d); //将时间对象按照格式化字符串,转化成字符串
System.out.println(str);
System.out.println("####################");
String str2 = "1977-7-7";
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d2 = df2.parse(str2);
System.out.println(d2);
} catch (ParseException e) {
e.printStackTrace();
}
}
}</span>
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;
/**
* 可视化日历程序
* @author dell
*
*/
public class VisualCalendar {
public static void main(String[] args) {
System.out.println("请输入日期(按照格式:2030-3-10):");
Scanner scanner = new Scanner(System.in);
String temp = scanner.nextLine();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = format.parse(temp);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int day = calendar.get(Calendar.DATE);
calendar.set(Calendar.DATE, 1);
int maxDate = calendar.getActualMaximum(Calendar.DATE);
System.out.println("日\t一\t二\t三\t四\t五\t六");
for(int i=1;i
import java.io.File;
public class FileTree {
public static void main(String[] args) {
//找一个自己硬盘上有用的文件夹
File f = new File("d:/aaa");
printFile(f, 0);
}
static void printFile(File file,int level){
for (int i = 0; i < level; i++) {
System.out.print("-");
}
System.out.println(file.getName());
if(file.isDirectory()){
File[] files = file.listFiles();
for (File temp : files) {
printFile(temp, level+1);
}
}
}
}
子类的异常不能超父类
<span style="font-size:14px;">import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
class A {
public void method() throws IOException { }
}
// class D extends A { public void method() throws Exception { } //超过父类异常的范围,会报错!
// }
class E extends A { public void method() throws IOException, FileNotFoundException { }
}</span>
自己编写equals:
<span style="font-size:14px;"> public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (id != other.id)
return false;
return true;
}</span>
Set:无序不可重复(equals)
List:有序可重复。
Map:key不可重复
<span style="font-size:14px;">public class TestSet {
public static void main(String[] args) {
Set set = new HashSet();
set.add("aaa");
set.add("bbb");
set.add(new String("aaa"));
System.out.println(set.size());
System.out.println(set.contains("aaa"));
set.remove("aaa");
}
}</span>
//ArrayList:底层实现时数组,线程不安全,效率高。所以,查询快。修改、插入、删除慢。
//LinkedList:底层实现是链表,线程不安全,效率高。所以,查询慢。修改、插入、删除快。
//Vector:线程安全的,效率低。
/**
* 自己实现一个ArrayList,帮助我们更好的理解ArrayList类的底层结构!
*
*/
public class SxtArrayList /*implements List*/ {
private Object[] elementData;
private int size;
public int size(){
return size;
}
public boolean isEmpty(){
return size==0;
}
public SxtArrayList(){
this(10);
}
public SxtArrayList(int initialCapacity){
if(initialCapacity<0){
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
elementData = new Object[initialCapacity];
}
public void add(Object obj){
//数组扩容和数据的拷贝
if(size==elementData.length){
Object[] newArray = new Object[size*2+1];
System.arraycopy(elementData, 0, newArray, 0, elementData.length);
// for(int i=0;i<elementData.length;i++){
// newArray[i] = elementData[i];
// }
elementData = newArray;
}
elementData[size++]=obj;
// size++;
}
public Object get(int index){
rangeCheck(index);
return elementData[index];
}
public void remove(int index){
rangeCheck(index);
//删除指定位置的对象
//a b d e
int numMoved = size - index - 1;
if (numMoved > 0){
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
}
elementData[--size] = null; // Let gc do its work
}
public void remove(Object obj){
for(int i=0;i<size;i++){
if(get(i).equals(obj)){ //注意:底层调用的equals方法而不是==.
remove(i);
}
}
}
public Object set(int index,Object obj){
rangeCheck(index);
Object oldValue = elementData[index];
elementData[index] = obj;
return oldValue;
}
public void add(int index,Object obj){
rangeCheck(index);
ensureCapacity(); //数组扩容
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = obj;
size++;
}
private void ensureCapacity(){
//数组扩容和数据的拷贝
if(size==elementData.length){
Object[] newArray = new Object[size*2+1];
System.arraycopy(elementData, 0, newArray, 0, elementData.length);
elementData = newArray;
}
}
private void rangeCheck(int index){
if(index<0||index>=size){
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
SxtArrayList list = new SxtArrayList(3);
list.add("333");
list.add("444");
list.add("5");
list.add("344433");
list.add("333");
list.add("333");
System.out.println(list.size());
list.remove("444");
System.out.println(list.size());
}
}
自实现linkedList
public class Node {
Node previous; //上一个节点
Object obj;
Node next; //下一个节点
public Node() {
}
public Node(Node previous, Object obj, Node next) {
super();
this.previous = previous;
this.obj = obj;
this.next = next;
}
public Node getPrevious() {
return previous;
}
public void setPrevious(Node previous) {
this.previous = previous;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public class SxtLinkedList /*implements List*/ {
private Node first;
private Node last;
private int size;
public void add(Object obj){
Node n = new Node();
if(first==null){
n.setPrevious(null);
n.setObj(obj);
n.setNext(null);
first = n;
last = n;
}else{
//直接往last节点后增加新的节点
n.setPrevious(last);
n.setObj(obj);
n.setNext(null);
last.setNext(n);
last = n;
}
size++;
}
public int size(){
return size;
}
private void rangeCheck(int index){
if(index<0||index>=size){
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public Object get(int index){ //2
rangeCheck(index);
// 0 1 2 3 4
Node temp = node(index);
if(temp!=null){
return temp.obj;
}
return null;
}
public Node node(int index){
Node temp = null;
if(first!=null){
if (index < (size >> 1)) {
temp = first;
for(int i=0;i<index;i++){
temp = temp.next;
}
}else{
temp = last;
for (int i = size - 1; i > index; i--){
temp = temp.previous;
}
}
}
// LinkedList l;
return temp;
}
public void remove(int index){
Node temp = node(index);
if(temp!=null){
Node up = temp.previous;
Node down = temp.next;
up.next = down;
down.previous = up;
size--;
}
}
public void add(int index,Object obj){
Node temp = node(index);
Node newNode = new Node();
newNode.obj = obj;
if(temp!=null){
Node up = temp.previous;
up.next = newNode;
newNode.previous = up;
newNode.next = temp;
temp.previous = newNode;
size++;
}
}
public static void main(String[] args) {
SxtLinkedList list = new SxtLinkedList();
list.add("aaa");
list.add("bbb");
// list.add(1,"BBBB");
list.add("ccc");
list.add("ddd");
list.add("eee");
// list.remove(1);
System.out.println(list.get(3));
}
}
自实现MAP
class SxtEntry {
Object key;
Object value;
public SxtEntry(Object key, Object value) {
super();
this.key = key;
this.value = value;
}
}
public class SxtMap002 {
LinkedList[] arr = new LinkedList[9]; //Map的底层结构就是:数组+链表!
int size;
public void put(Object key,Object value){
SxtEntry e = new SxtEntry(key,value);
int hash = key.hashCode();
hash = hash<0?-hash:hash;
int a = hash%arr.length;
if(arr[a]==null){
LinkedList list = new LinkedList();
arr[a] = list;
list.add(e);
}else{
LinkedList list = arr[a];
for(int i=0;i<list.size();i++){
SxtEntry e2 = (SxtEntry) list.get(i);
if(e2.key.equals(key)){
e2.value = value; //键值重复直接覆盖!
return;
}
}
arr[a].add(e);
}
//a:1000-->1 b:10000-->13
}
public Object get(Object key){
int a = key.hashCode()%arr.length;
if(arr[a]!=null){
LinkedList list = arr[a];
for(int i=0;i<list.size();i++){
SxtEntry e = (SxtEntry) list.get(i);
if(e.key.equals(key)){
return e.value;
}
}
}
return null;
}
public static void main(String[] args) {
SxtMap002 m = new SxtMap002();
m.put("高琪", new Wife("杨幂"));
m.put("高琪", new Wife("李四"));
Wife w = (Wife) m.get("高琪");
System.out.println(w.name);
}
}
/**
* 自定义自己的HashSet
* @author Administrator
*
*/
public class SxtHashSet {
HashMap map;
private static final Object PRESENT = new Object();
public SxtHashSet(){
map = new HashMap();
}
public int size(){
return map.size();
}
public void add(Object o){
map.put(o, PRESENT); //set的不可重复就是利用了map里面键对象的不可重复!
}
public static void main(String[] args) {
SxtHashSet s = new SxtHashSet();
s.add("aaa");
s.add(new String("aaa"));
System.out.println(s.size());
}
}
迭代器
public class Test01 {
public static void main(String[] args) {
List list = new ArrayList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
//通过索引遍历List
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
//通过迭代器遍历List
for(Iterator iter2 = list.iterator();iter2.hasNext();){
String str = (String) iter2.next();
System.out.println(str);
iter2.remove();
iter2.remove();
}
System.out.println(list.size()+"******");
Set set = new HashSet();
set.add("高1");
set.add("高2");
set.add("高3");
//通过迭代器遍历Set
// Iterator iter = set.iterator();
// while(iter.hasNext()){
for(Iterator iter = set.iterator();iter.hasNext();){
String str = (String) iter.next();
System.out.println(str);
}
}
}
public class Test02 {
public static void main(String[] args) {
Map map = new HashMap();
map.put("aa", "aaaa");
map.put("bb", "bbbb");
//遍历Map的第一种方式
Set keys = map.keySet();
for(Iterator iter = keys.iterator();iter.hasNext();){
String keyStr = (String) iter.next();
System.out.println(keyStr+"---"+map.get(keyStr));
}
//遍历Map的第二种方式
Set<Entry> set2 = map.entrySet();
for(Iterator iter = set2.iterator();iter.hasNext();){
Entry e = (Entry) iter.next();
System.out.println(e.getKey()+"---"+e.getValue());
}
}
}
排序的两种方式:
1、实体类 java.lang.Comparable +compareTo
2、业务排序类 java.util.Comparator +compare
方式1:
class Worker implements java.lang.Comparable<Worker> {
//工种
private String type;
//工资
private double salary;
public Worker() {
// TODO Auto-generated constructor stub
}
public Worker(String type, double salary) {
super();
this.type = type;
this.salary = salary;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
/**
* 按工资升序
*/
@Override
public int compareTo(Worker o) {
return this.salary>o.salary?1:( this.salary==o.salary?0:-1);
}
@Override
public String toString() {
return "工种:"+this.type+",工资:"+this.salary+"\n";
}
}
public class TreeMapDemo02 {
/**
* @param args
*/
public static void main(String[] args) {
Worker w1 =new Worker("垃圾回收员",12000);
Worker w2 =new Worker("农民工",8000);
Worker w3 =new Worker("程序猿",5000);
TreeMap<Worker,String > employees =new TreeMap<Worker,String >();
employees.put(w1,"bjsxt");
employees.put(w2,"bjsxt");
employees.put(w3,"bjsxt");
System.out.println(employees.keySet());
}
}
方式2:
class Person {
private final String name;//名称
private final int handsome;//帅气指数
public Person() {
name =null;
handsome =0;
}
public Person(String name, int handsome) {
super();
this.name = name;
this.handsome = handsome;
}
public String getName() {
return name;
}
public int getHandsome() {
return handsome;
}
@Override
public String toString() {
return "姓名:"+this.name+",帅气指数:"+this.handsome+"\n";
}
}
public class TreeMapDemo {
/**
* @param args
*/
public static void main(String[] args) {
Person p1 =new Person("您",100);
Person p2 =new Person("刘德华",1000);
Person p3 =new Person("梁朝伟",1200);
Person p4 =new Person("老裴",50);
TreeMap<Person,String> map =new TreeMap<Person,String>(new java.util.Comparator<Person>(){
@Override
public int compare(Person o1, Person o2) {
return -(o1.getHandsome()-o2.getHandsome());
}
} );
map.put(p1, "bjsxt");
map.put(p2, "bjsxt");
map.put(p3, "bjsxt");
map.put(p4, "bjsxt");
//查看键
Set<Person> persons =map.keySet();
System.out.println(persons);
}
}
1、TreeSet:数据元素可以排序且不可重复
对比:Set接口:HashSet,元素必须重写 hashcode和equals方法。
去重:比较等于0即重复
1)、元素可以排序 java.lang.Comparable +compareTo
new TreeSet()
2)、排序业务类 java.util.Comparator +compare
new TreeSet(Comparator<? super E> comparator)
注意:在添加数据时排序,数据更改不会影响原来的顺序,不要修改数据,否则可能重复
2、TreeMap:要求键 可以排序,与上TreeSet同理
/**
* 泛型类:声明时使用泛型
* 字母:
* T Type 表示类型。
K V 分别代表键值中的Key Value。
E 代表Element。
使用时确定类型
注意:
1、泛型只能使用引用类型,不能基本类型
2、泛型声明时字母不能使用 静态属性|静态方法上
* @author Administrator
*
* @param <T>
*/
public class Student<T1,T2> {
private T1 javaScore;
private T2 oracleScore;
//泛型声明时不能使用 静态属性|静态方法上
//private static T1 test;
public T1 getJavaScore() {
return javaScore;
}
public void setJavaScore(T1 javaScore) {
this.javaScore = javaScore;
}
public T2 getOracleScore() {
return oracleScore;
}
public void setOracleScore(T2 oracleScore) {
this.oracleScore = oracleScore;
}
/**
* @param args
*/
public static void main(String[] args) {
//使用时指定类型(引用类型)
Student<String,Integer> stu = new Student<String,Integer> ();
//1、安全:类型检查
stu.setJavaScore("优秀");
//2、省心:类型转换
int it =stu.getOracleScore(); //自动拆箱
}
}
泛型 :
/**
* 父类为泛型类
* 1、属性
* 2、方法
*
* 要么同时擦除,要么子类大于等于父类的类型,
* 不能子类擦除,父类泛型
* 1、属性类型
* 父类中,随父类而定
* 子类中,随子类而定
* 2、方法重写:
* 随父类而定
*
*
* @author Administrator
*
* @param <T>
*/
public abstract class Father<T,T1> {
T name;
public abstract void test(T t);
}
/**
* 子类声明时指定具体类型
* 属性类型为具体类型
* 方法同理
*/
class Child1 extends Father<String,Integer>{
String t2;
@Override
public void test(String t) {
}
}
/**
* 子类为泛型类 ,类型在使用时确定
* @author Administrator
*
*/
class Child2<T1,T,T3> extends Father<T,T1>{
T1 t2;
@Override
public void test(T t) {
}
}
/**
* 子类为泛型类,父类不指定类型 ,泛型的擦除,使用Object替换
*/
class Child3<T1,T2> extends Father{
T1 name2;
@Override
public void test(Object t) {
// TODO Auto-generated method stub
}
}
/**
* 子类与父类同时擦除
*/
class Child4 extends Father{
String name;
@Override
public void test(Object t) {
}
}
/**
*错误:子类擦除,父类使用泛型
class Child5 extends Father<T,T1>{
String name;
@Override
public void test(T t) {
}
*/
/**
*泛型的擦除
*1、继承|实现声明 不指定类型
*2、使用时 不指定类型
*统一Object 对待
*1、编译器警告 消除使用Object
*2、不完全等同于Object ,编译不会类型检查
* @author Administrator
*
* @param <T>
*/
public class Student<T> {
private T javaScore;
private T oracleScore;
//泛型声明时不能使用 静态属性|静态方法上
//private static T1 test;
public T getJavaScore() {
return javaScore;
}
public void setJavaScore(T javaScore) {
this.javaScore = javaScore;
}
public T getOracleScore() {
return oracleScore;
}
public void setOracleScore(T oracleScore) {
this.oracleScore = oracleScore;
}
/**
* @param args
*/
public static void main(String[] args) {
Student stu1 = new Student();
//消除警告 使用 Object
Student<Object> stu = new Student<Object>();
stu.setJavaScore("af"); //以Object对待
test(stu1); //stu1 相当于Object 但是不完全等同Object
//擦除,不会类型检查
//test(stu);--报错
test1(stu1);
test1(stu);
}
public static void test(Student<Integer> a){
}
public static void test1(Student<?> a){
}
}
/**
* 泛型接口:与继承同理
* 重写方法随父类而定
*
* @param <T>
*/
public interface Comparable<T> {
void compare(T t);
}
//声明子类指定具体类型
class Comp implements Comparable<Integer>{
@Override
public void compare(Integer t) {
// TODO Auto-generated method stub
}
}
//擦除
class Comp1 implements Comparable{
@Override
public void compare(Object t) {
// TODO Auto-generated method stub
}
}
//父类擦除,子类泛型
class Comp2<T> implements Comparable{
@Override
public void compare(Object t) {
// TODO Auto-generated method stub
}
}
//子类泛型>=父类泛型
class Comp3<T> implements Comparable<T>{
@Override
public void compare(T t) {
// TODO Auto-generated method stub
}
}
//父类泛型,子类擦除 错误
泛型木有多态
//泛型类
class A<T> {
}
public Fruit {
}
class Apple extends Fruit{
}
public class App {
/**
* @param args
*/
public static void main(String[] args) {
A<Fruit> f1 = new A<Apple>(); //没有多态 报错
A<Fruit> f =new A<Fruit>();
test(new A<Apple>()); // 形参没有多态 报错
}
//形参使用多态
public static void test(A<Fruit> f){
}
//返回类型使用多态 报错
public static A<Fruit> test2(){
return (A<Fruit>)(new A<Apple>());
}
}
/**
* 通配符
* ?类型不定,使用时确定类型
* ?使用:声明类型|声明方法上,不能声明类或使用时
* ? extends : <= 上限 指定类型 子类或自身
* ? super :>=下限 指定类型 为自身或父类
* @author Administrator
*
*/
//泛型类
class A<T> {
}
class Fruit {
}
class Apple extends Fruit{
}
public class Student<T> {
T score;
public static void main(String[] args) {
Student<?> stu = new Student<String>();
test(new Student<Integer>());
test2(new Student<Apple>());
//test3(new Student<Apple>()); //泛型没有多态
//test4(new Student<Apple>()); //<
stu = new Student<Fruit>();;
//test4(stu); //使用时确定类型
test4(new Student<Object>());
test4(new Student<Fruit>());
}
public static void test(Student<?> stu){
}
public static void test3(Student<Fruit> stu){
}
// <=
public static void test2(Student<? extends Fruit> stu){
}
//>=
public static void test4(Student<? super Fruit> stu){
}
}
/**
* 没有泛型数组
* 声明可以使用,但是创建失败
* @author Administrator
*
*/
public class Array {
/**
* @param args
*/
public static void main(String[] args) {
Integer[] arr = new Integer[4];
//Student<String>[] arr2 = new Student<String>[10];
Student<?>[] arr2 = new Student[10];
MyArrayList<String> strList =new MyArrayList<String>();
strList.add(0, "a");
String elem =strList.getElem(0);
System.out.println(elem);
}
}
class MyArrayList<E>{
//E[] cap =new E[10]; 没有泛型数组
Object[] cap = new Object[10];
public void add(int idx,E e){
cap[idx] =e;
}
@SuppressWarnings("unchecked")
public E[] getAll(){
return (E[]) cap;
}
@SuppressWarnings("unchecked")
public E getElem(int idx){
return (E) cap[idx];
}
}
一、Hashtable 与HashMap的区别 (面试题)
1、主要:Hashtable线程安全,同步,效率相对低下
HashMap 线程不安全,非同步,效率相对高
2、父类:Hashtable 是 Dictionary HashMap 是 AbstractMap
3、null: Hashtable键与值不能为null
HashMap 键最多一个null,值可以多个null
二、Properties
1、作用:读写资源配置文件
2、键与值只能为字符串
3、方法:
setProperty(String key, String value)
getProperty(String key)
getProperty(String key, String defaultValue)
后缀:.properties
store(OutputStream out, String comments)
store(Writer writer, String comments)
load(InputStream inStream)
load(Reader reader)
.xml
storeToXML(OutputStream os, String comment) :UTF-8字符集
storeToXML(OutputStream os, String comment, String encoding)
loadFromXML(InputStream in)
三、相对路径与绝对路径
1、绝对路径 : 盘符: /
2、相对路径 : 当前项目、工程
四、类路径加载资源文件
类所在的根路径
1、类.class.getResourceAsStream("/")
2、Thread.currentThread().getContextClassLoader().getResourceAsStream("")
一、引用分类(面试)
强引用:StrongReference:引用指向对象,gc (Garbage collection)运行时不回收
软引用:SoftReference gc运行时可能回收(jvm内存不够)
弱引用:WeakReference gc运行时立即回收
虚引用:PhantomReference 类似于无引用,主要跟踪对象被回收的状态,不能单独使用,必须与引用队列(ReferenceQueue) 联合使用
二、三个Map接口实现类
1、WeakHashMap:键为弱引用
2、IdentityHashMap:键比较地址去重,注意常量池的对象
3、EnumMap:枚举map,要求键为枚举的值
一、同步控制:多线程并发访问集合的线程安全。
常用容器 ArrayList HashSet HashMap 等都是线程不安全的
Collections提供了synchronizedXxx()方法,将指定容器包装成同步
synchronizedList()
synchronizedSet()
synchronizedMap()
二、不可变设置:“只读”访问, Collections提供了三种方法
emptyXxx() 空的不可变的集合
singletonXxx() 一个元素不可变的集合
unmodifiableXxx() 不可变容器
二、三个知识点
1、迭代器
1)、java.util.Iterator + hasNext() next() remove()
2)、foreach :java.lang.Iterable +iterator()
2、比较器
1)、实体类可以排序 java.lang.Comparable +compareTo
2)、排序比较器(解耦、多种排序规则) java.util.Comparator +compare
List+Collections.sort()
TreeSet
TreeMap
3、泛型: <> 泛型类、泛型方法、泛型接口、泛型擦除、通配符 ? extends super 泛型嵌套
三、六个接口
Collection Set List Map Iterator Comparable
四、九个常用类 添加、删除、修改、查看 +遍历
1、ArrayList:数组 查看多于修改
add(元素) add(索引,元素) remove(元素) remove(索引) set(索引,元素) get(索引)
for+get foreach() Iterator ListIterator
2、LinkedList :链表,修改多于查看 ,多了些链头与链尾的方法
3、HashSet: 重写 hashcode +equals
add(元素) remove(元素)
foreach() Iterator
4、TreeSet :元素可以排序 或者提供排序的业务类
5、HashMap: 键不能重复 必须重写 hashcode +equals ,值可以重复
put(k,v) remove(k) get(K) containsKey containsValue
获取值:values() keySet()+get entrySet()+getValue()
获取键:keySet entrySet() +getKey()
获取键与值: keySet()+get entrySet() +getKey() getValue()
6、Properties :资源配置文件 相对路径获取文件
7、Hashtable:键与值都不能为null 线程安全
8、Stack:栈
9、Collections:工具类
写配置文件:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
/**
* 使用Properties 输出到文件
* 资源配置文件:
*
* 1、.properties
* store(OutputStream out, String comments)
store(Writer writer, String comments)
2、.xml
storeToXML(OutputStream os, String comment) :UTF-8字符集
storeToXML(OutputStream os, String comment, String encoding)
* @author Administrator
*
*/
public class Demo02 {
/**
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
//创建对象
Properties pro =new Properties();
//存储
pro.setProperty("driver", "oracle.jdbc.driver.OracleDriver");
pro.setProperty("url", "jdbc:oracle:thin:@localhost:1521:orcl");
pro.setProperty("user", "scott");
pro.setProperty("pwd", "tiger");
//存储到e:/others 绝对路径 盘符:
//pro.store(new FileOutputStream(new File("e:/others/db.properties")), "db配置");
//pro.storeToXML(new FileOutputStream(new File("e:/others/db.xml")), "db配置");
//使用相对路径 当前的工程
// pro.store(new FileOutputStream(new File("db.properties")), "db配置");
// pro.store(new FileOutputStream(new File("src/db.properties")), "db配置");
pro.store(new FileOutputStream(new File("src/com/bjsxt/others/pro/db.properties")), "db配置");
}
}
读配置文件:
import java.io.IOException;
import java.util.Properties;
/**
* 使用类相对路径读取配置文件
* bin
* @author Administrator
*
*/
public class Demo04 {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Properties pro =new Properties();
//类相对路径的 / bin
//pro.load(Demo04.class.getResourceAsStream("/com/bjsxt/others/pro/db.properties"));
//"" bin
pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("com/bjsxt/others/pro/db.properties"));
System.out.println(pro.getProperty("user", "bjsxt"));
}
}
//队列应用例子
import java.util.ArrayDeque;
import java.util.Deque;
/**
* 使用队列实现自定义堆栈
* 1、弹
* 2、压
* 3、获取头
* @author Administrator
*
* @param <E>
*/
class MyStack<E> {
//容器
private Deque<E> container =new ArrayDeque<E>();
//容量
private int cap;
public MyStack(int cap) {
super();
this.cap = cap;
}
//压栈
public boolean push(E e){
if(container.size()+1>cap){
return false;
}
return container.offerLast(e);
}
//弹栈
public E pop(){
return container.pollLast();
}
//获取
public E peek(){
return container.peekLast();
}
public int size(){
return this.container.size();
}
}
public class Demo02 {
/**
* @param args
*/
public static void main(String[] args) {
MyStack<String> backHistory =new MyStack<String>(3);
backHistory.push("www.baidu.com");
backHistory.push("www.google.com");
backHistory.push("www.sina.com");
backHistory.push("www.bjsxt.cn");
System.out.println("大小:"+backHistory.size());
//遍历
String item=null;
while(null!=(item=backHistory.pop())){
System.out.println(item);
}
}
}
list,set,map支持线程同步的方法
/**
* 使用Collections管理同步 容器
* synchronizedList()
synchronizedSet()
synchronizedMap()
* @author Administrator
*
*/
public class Demo01 {
/**
* @param args
*/
public static void main(String[] args) {
List<String> list =new ArrayList<String>();
list.add("a");
list.add("b");
//list可以同步
List<String> synList =Collections.synchronizedList(list);
System.out.println("线程安全的list制作完毕");
}
}
Collection对列表的支持
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 只读设置
* emptyXxx() 空的不可变的集合
* 1、emptyList()
* emptyMap()
* emptySet()
2、singletonXxx() 一个元素不可变的集合
singleton(T o)
singletonList(T o)
singletonMap(K key, V value)
3、unmodifiableXxx() 不可变容器
unmodifiableList(List<? extends T> list)
unmodifiableSet(Set<? extends T> s)
unmodifiableMap(Map<? extends K,? extends V> m)
* @author Administrator
*
*/
public class Demo02 {
/**
* @param args
*/
public static void main(String[] args) {
Map<String,String> map =new HashMap<String,String>();
map.put("test", "test");
map.put("bjsxt", "bjsxt");
//只读控制
Map<String,String> map2 =Collections.unmodifiableMap(map);
//map2.put("a", "a"); //不能操作
System.out.println(map2.size());
//一个元素的容器测试
List<String> list =Collections.singletonList(new String());
list.add("test");
//list.add("bjsxt"); //只能包含一个元素的容器
}
public static Set<String> oper(Set<String> set){
if(null==set){
return Collections.EMPTY_SET; //外部获取避免NullPointerException
}
//操作
return set;
}
}
import java.util.EnumMap;
/**
* EnumMap要求键为枚举
* @author Administrator
*
*/
public class EnumMapDemo {
/**
* @param args
*/
public static void main(String[] args) {
EnumMap<Season,String> map =new EnumMap<Season,String>(Season.class);
//存放值
map.put(Season.SPRING, "春困");
map.put(Season.SUMMER, "夏无力");
map.put(Season.AUTUMN, "秋乏");
map.put(Season.WINTER, "冬眠");
System.out.println(map.size());
}
}
//季节
enum Season{
SPRING,SUMMER,AUTUMN,WINTER
}
import java.util.WeakHashMap;
/**
* WeakHashMap 键为弱类型,gc运行立即回收
* @author Administrator
*
*/
public class WeakHashMapDemo {
/**
* @param args
*/
public static void main(String[] args) {
WeakHashMap<String,String> map =new WeakHashMap<String,String>();
//测试数据
//常量池对象,不会回收
map.put("abc", "a");
map.put("d", "test");
//gc运行 已被回收
map.put(new String("bjsxt"), "c");
map.put(new String("dsf"), "d");
//通知回收
System.gc();
System.runFinalization();
System.out.println(map.size());
}
}
import java.util.IdentityHashMap;
/**
* IdentityHashMap 键比较地址去重
* @author Administrator
*
*/
public class A {
/**
* @param args
*/
public static void main(String[] args) {
IdentityHashMap<String ,String> map =new IdentityHashMap<String,String>();
//常量池中的"a"
map.put("a", "a1");
map.put("a", "a2");
System.out.println(map.size()); //1
map.put(new String("a"), "a3");
map.put(new String("a"), "a4");
System.out.println(map.size()); //3
}
}
import java.lang.ref.WeakReference;
/**
* 引用分类:强、软、弱、虚
* 强与弱引用
* @author Administrator
*
*/
public class RefDemo {
/**
* @param args
*/
public static void main(String[] args) {
//字符串常量池
String str =new String("bjsxt is very good");
//弱引用 管理 对象
WeakReference<String> wr =new WeakReference<String>(str);
System.out.println("gc运行前:"+wr.get());
//断开引用
str =null;
//通知回收
System.gc();
System.runFinalization();
//对象被回收
System.out.println("gc运行后:"+wr.get());
}
public static void testStrong(){
//字符串常量池 共享(不能回收)
String str ="bjsxt is very good";
//弱引用 管理 对象
WeakReference<String> wr =new WeakReference<String>(str);
System.out.println("gc运行前:"+wr.get());
//断开引用
str =null;
//通知回收
System.gc();
System.runFinalization();
System.out.println("gc运行后:"+wr.get());
}
}