diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..5e64050 --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding//src/btp/oneP/BufferToText.java=UTF-8 diff --git a/src/Data/IO.jpg b/src/Data/IO.jpg new file mode 100644 index 0000000..71e5e49 Binary files /dev/null and b/src/Data/IO.jpg differ diff --git a/src/btp/oneP/ABtpTest.java b/src/btp/oneP/ABtpTest.java index 36bdcce..efdc18c 100644 --- a/src/btp/oneP/ABtpTest.java +++ b/src/btp/oneP/ABtpTest.java @@ -6,6 +6,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Scanner; +import java.util.zip.DeflaterOutputStream; public class ABtpTest { diff --git a/src/btp/oneP/ApplyTest.java b/src/btp/oneP/ApplyTest.java index 08e3eef..611501f 100644 --- a/src/btp/oneP/ApplyTest.java +++ b/src/btp/oneP/ApplyTest.java @@ -35,7 +35,7 @@ public static void main(String[] args) throws NoSuchMethodException, SecurityExc shapeQ.add(new Shape()); shapeQ.add(new Square()); } - Apply.apply(shapeQ, Shape.class.getMethod("rotate")); + Apply.apply(shapeQ, ShapeX.class.getMethod("rotate")); } } diff --git a/src/btp/oneP/AssociativeArray.java b/src/btp/oneP/AssociativeArray.java new file mode 100644 index 0000000..fb4213a --- /dev/null +++ b/src/btp/oneP/AssociativeArray.java @@ -0,0 +1,57 @@ +package btp.oneP; + +public class AssociativeArray{ + + public static void main(String[] args) { + AssociativeArray map = new AssociativeArray(6); + map.put("sky", "blue"); + map.put("grass", "green"); + map.put("ocean", "dancing"); + map.put("tree", "tall"); + map.put("earth", "brown"); + map.put("sun", "warm"); + try{ + map.put("extra", "object"); + }catch(Exception e){ + System.out.println(e); + } + System.out.println(map); + System.out.println(map.get("ocean")); + } + + private Object[][] pair; + private int index; + public AssociativeArray(int length){ + pair = new Object[length][2]; + } + + public void put(K key,V value){ + if(index >= pair.length){ + throw new ArrayIndexOutOfBoundsException(); + } + pair[index++] = new Object[]{key,value}; + } + + @SuppressWarnings("unchecked") + public V get(K key){ + for(int i=0;i charSets = Charset.availableCharsets(); + Iterator it = charSets.keySet().iterator(); + while(it.hasNext()){ + String csName = it.next(); + System.out.print(csName); + Iterator aliases = charSets.get(csName).aliases().iterator(); + if(aliases.hasNext()){ + System.out.print(": "); + } + while(aliases.hasNext()){ + System.out.print(aliases.next()); + if(aliases.hasNext()){ + System.out.print(", "); + } + } + System.out.println(); + } + } + +} diff --git a/src/btp/oneP/BasicFileOutput.java b/src/btp/oneP/BasicFileOutput.java new file mode 100644 index 0000000..c9f9cc7 --- /dev/null +++ b/src/btp/oneP/BasicFileOutput.java @@ -0,0 +1,24 @@ +package btp.oneP; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; + +public class BasicFileOutput { + static String file = "C:\\Users\\dell\\Desktop\\IO\\io.txt"; + public static void main(String[] args) throws IOException { + BufferedReader in = new BufferedReader(new StringReader(BufferedInputFile.read("E:\\workspaces\\NewWork\\Study\\src\\btp\\oneP\\BasicFileOutput.java"))); + PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file))); + int lineCount = 1; + String s; + while((s = in.readLine()) != null){ + out.println(lineCount++ + " : " + s); + } + out.close(); + System.out.println(BufferedInputFile.read(file)); + } + +} diff --git a/src/btp/oneP/BinaryFile.java b/src/btp/oneP/BinaryFile.java new file mode 100644 index 0000000..2e31bfe --- /dev/null +++ b/src/btp/oneP/BinaryFile.java @@ -0,0 +1,38 @@ +package btp.oneP; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class BinaryFile { + public static byte[] read(File bFile) throws IOException{ + BufferedInputStream bf = new BufferedInputStream(new FileInputStream(bFile)); + try{ + byte[] data = new byte[bf.available()]; + bf.read(data); + return data; + }finally{ + bf.close(); + } + } + + public static byte[] read(String bFile) throws IOException{ + return read(new File(bFile).getAbsoluteFile()); + } + public static void main(String[] args) throws IOException { + byte[] bytes = read("E:\\workspaces\\NewWork\\Study\\src\\btp\\oneP\\BinaryFile.java"); + Map map = new HashMap(); + for(byte b : bytes){ + if(null == map.get(b)){ + map.put(b, 1); + }else{ + map.put(b, map.get(b)+1); + } + } + System.out.println(map); + } + +} diff --git a/src/btp/oneP/Bits.java b/src/btp/oneP/Bits.java new file mode 100644 index 0000000..754bdee --- /dev/null +++ b/src/btp/oneP/Bits.java @@ -0,0 +1,67 @@ +package btp.oneP; + +import java.util.BitSet; +import java.util.Random; + +public class Bits { + public static void printBitSet(BitSet b){ + System.out.println("bits: "+b); + StringBuilder bbits = new StringBuilder(); + for(int j = 0;j < b.size();j++){ + bbits.append(b.get(j)?"1":"0"); + } + System.out.println("bit pattern: "+bbits); + } + public static void main(String[] args) { + // TODO Auto-generated method stub + Random rand = new Random(47); + byte bt = (byte)rand.nextInt(); + BitSet bb = new BitSet(); + for(int i = 7;i>=0;i--){ + if(((1 << i)&bt) != 0){ + bb.set(i); + }else{ + bb.clear(i); + } + } + System.out.println("byte value: "+bt); + printBitSet(bb); + + short st = (short)rand.nextInt(); + BitSet bs = new BitSet(); + for(int i = 15;i>=0;i--){ + if(((1 << i)&st) != 0){ + bs.set(i); + }else{ + bs.clear(i); + } + } + System.out.println("short value: "+st); + printBitSet(bs); + + int it = rand.nextInt(); + BitSet bi = new BitSet(); + for(int i = 31;i>=0;i--){ + if(((1 << i)&bt) != 0){ + bi.set(i); + }else{ + bi.clear(i); + } + } + System.out.println("int value: "+it); + printBitSet(bi); + + BitSet b127 = new BitSet(); + b127.set(127); + System.out.println("set bit 127: "+b127); + BitSet b255 = new BitSet(65); + b255.set(255); + System.out.println("set bit 255: "+b255); + + BitSet b1023 = new BitSet(512); + b1023.set(1023); + b1023.set(1024); + System.out.println("set bit 1023: "+b1023); + } + +} diff --git a/src/btp/oneP/Blip3.java b/src/btp/oneP/Blip3.java new file mode 100644 index 0000000..65d8ec3 --- /dev/null +++ b/src/btp/oneP/Blip3.java @@ -0,0 +1,55 @@ +package btp.oneP; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.Externalizable; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectInputStream; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; + +public class Blip3 implements Externalizable { + private int i; + private String s; + public Blip3(){ + System.out.println("Blip3 Constructor"); + } + public Blip3(String x,int a){ + System.out.println("Blip3(String x,int a)"); + s = x; + i = a; + } + public String toString(){ + return s + i; + } + + @Override + public void writeExternal(ObjectOutput out) throws IOException { + System.out.println("Blip3.writeExternal"); + out.writeObject(s); + out.writeInt(i); + } + + @Override + public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + // TODO Auto-generated method stub + System.out.println("Blip3.readExternal"); + s = (String)in.readObject(); + i = in.readInt(); + } + + public static void main(String[] args) throws IOException, ClassNotFoundException { + // TODO Auto-generated method stub + Blip3 b3 = new Blip3("A string",47); + System.out.println(b3); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream o = new ObjectOutputStream(bout); + o.writeObject(b3); + o.close(); + ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray())); + b3 = (Blip3) in.readObject(); + System.out.println(b3); + } + +} diff --git a/src/btp/oneP/Blips.java b/src/btp/oneP/Blips.java new file mode 100644 index 0000000..8601896 --- /dev/null +++ b/src/btp/oneP/Blips.java @@ -0,0 +1,64 @@ +package btp.oneP; + +import java.io.Externalizable; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectInputStream; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; + +public class Blips { + + public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { + Blip1 b1 = new Blip1(); + Blip2 b2 = new Blip2(9); + ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\Blips.out")); + o.writeObject(b1); + o.writeObject(b2); + o.close(); + + ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:\\Users\\dell\\Desktop\\IO\\Blips.out")); + b1 = (Blip1) in.readObject(); + b2 = (Blip2) in.readObject(); + + } + +} + +class Blip1 implements Externalizable{ + public Blip1(){ + System.out.println("Blip1 Constructor"); + } + + @Override + public void writeExternal(ObjectOutput out) throws IOException { + System.out.println("Blip1.writeExternal"); + } + + @Override + public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + System.out.println("Blip1.readExternal"); + } + +} + +//实现Externalizable接口的类必须要提供public的无参数的构造器,不然会报错。Serializable则不需要 +class Blip2 implements Externalizable{ + public Blip2(int i){ + System.out.println("Blip2 Constructor"); + } + + @Override + public void writeExternal(ObjectOutput out) throws IOException { + System.out.println("Blip2.writeExternal"); + } + + @Override + public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + System.out.println("Blip2.readExternal"); + } + +} diff --git a/src/btp/oneP/BufferToText.java b/src/btp/oneP/BufferToText.java new file mode 100644 index 0000000..b4b71ca --- /dev/null +++ b/src/btp/oneP/BufferToText.java @@ -0,0 +1,51 @@ +package btp.oneP; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.Charset; + +public class BufferToText { + private static final int BSIZE = 1024; + public static void main(String[] args) throws IOException { + FileChannel fc = new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\data2.txt").getChannel(); + fc.write(ByteBuffer.wrap("some text".getBytes())); + fc.close(); + + fc = new FileInputStream("C:\\Users\\dell\\Desktop\\IO\\data2.txt").getChannel(); + ByteBuffer buff = ByteBuffer.allocate(BSIZE); + fc.read(buff); + buff.flip(); + System.out.println(buff.asCharBuffer()); + buff.rewind(); + + String encoding = System.getProperty("file.encoding"); + System.out.println("Decoded using "+encoding+":"+Charset.forName(encoding).decode(buff)); + + fc = new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\data2.txt").getChannel(); + fc.write(ByteBuffer.wrap("Some text".getBytes("GBK"))); + fc.close(); + + fc = new FileInputStream("C:\\Users\\dell\\Desktop\\IO\\data2.txt").getChannel(); + buff.clear(); + fc.read(buff); + buff.flip(); + System.out.println(buff.asCharBuffer()); + System.out.println("Decoded using "+"GBK"+":"+Charset.forName("GBK").decode(buff)); + + fc = new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\data2.txt").getChannel(); + buff = ByteBuffer.allocate(24); + buff.asCharBuffer().put("Some text!"); + fc.write(buff); + fc.close(); + + fc = new FileInputStream("C:\\Users\\dell\\Desktop\\IO\\data2.txt").getChannel(); + buff.clear(); + fc.read(buff); + buff.flip(); + System.out.println(buff.asCharBuffer()); + } + +} diff --git a/src/btp/oneP/BufferedInputFile.java b/src/btp/oneP/BufferedInputFile.java new file mode 100644 index 0000000..57eb3e2 --- /dev/null +++ b/src/btp/oneP/BufferedInputFile.java @@ -0,0 +1,23 @@ +package btp.oneP; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class BufferedInputFile { + + public static String read(String filename) throws IOException{ + BufferedReader im = new BufferedReader(new FileReader(filename)); + String s; + StringBuilder sb = new StringBuilder(); + while((s = im.readLine()) != null){ + sb.append(s+"\n"); + } + im.close(); + return sb.toString(); + } + public static void main(String[] args) throws IOException { + System.out.println(read("E:\\workspaces\\NewWork\\Study\\src\\btp\\oneP\\BufferedInputFile.java")); + } + +} diff --git a/src/btp/oneP/CanonicalMapping.java b/src/btp/oneP/CanonicalMapping.java new file mode 100644 index 0000000..3743bd6 --- /dev/null +++ b/src/btp/oneP/CanonicalMapping.java @@ -0,0 +1,26 @@ +package btp.oneP; + +import java.util.WeakHashMap; + +public class CanonicalMapping { + + public static void main(String[] args) { + int size = 1000; + if(args.length > 0){ + size = new Integer(args[0]); + } + + Key[] keys = new Key[size]; + WeakHashMap map = new WeakHashMap(); + for(int i = 0;i < size; i++){ + Key k = new Key(Integer.toString(i)); + Value v = new Value(Integer.toString(i)); + if(i % 3 == 0){ + keys[i] = k; + } + map.put(k, v); + } + System.gc(); + } + +} diff --git a/src/btp/oneP/CarWash.java b/src/btp/oneP/CarWash.java new file mode 100644 index 0000000..20c1e3e --- /dev/null +++ b/src/btp/oneP/CarWash.java @@ -0,0 +1,89 @@ +package btp.oneP; + +import java.util.EnumSet; + +public class CarWash { + enum Cycle{ + UNDERBODY{ + + @Override + void action() { + System.out.println("Spraying the underbody"); + } + + }, + WHEELWASH{ + + @Override + void action() { + System.out.println("Washing the wheels"); + } + + }, + PREWASH{ + + @Override + void action() { + System.out.println("Loosening the dirt"); + } + + }, + BASIC{ + + @Override + void action() { + System.out.println("The basic wash"); + } + + }, + HOTWAX{ + + @Override + void action() { + System.out.println("Applying hot wax"); + } + + }, + RINSE{ + + @Override + void action() { + System.out.println("Rinsing"); + } + + }, + BLOWDRY{ + + @Override + void action() { + System.out.println("Blowing dry"); + } + + }; + abstract void action(); + } + EnumSet cycles = EnumSet.of(Cycle.BASIC, Cycle.RINSE); + public void add(Cycle cycle){ + cycles.add(cycle); + } + public void washCar(){ + for(Cycle c : cycles){ + c.action(); + } + } + public String toString(){ + return cycles.toString(); + } + public static void main(String[] args) { + CarWash wash = new CarWash(); + System.out.println(wash); + wash.washCar(); + wash.add(Cycle.BLOWDRY); + wash.add(Cycle.BLOWDRY); + wash.add(Cycle.RINSE); + wash.add(Cycle.HOTWAX); + System.out.println(wash); + wash.washCar(); + } + +} diff --git a/src/btp/oneP/ChangeCollectionTest.java b/src/btp/oneP/ChangeCollectionTest.java new file mode 100644 index 0000000..f68b4e3 --- /dev/null +++ b/src/btp/oneP/ChangeCollectionTest.java @@ -0,0 +1,19 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class ChangeCollectionTest { + + public static void main(String[] args) { + List list = new ArrayList(); + list.add("hh"); + Iterator it = list.iterator(); + //list.add("hh"); + while(it.hasNext()){ + it.remove(); + } + } + +} diff --git a/src/btp/oneP/ChangeSystemOut.java b/src/btp/oneP/ChangeSystemOut.java new file mode 100644 index 0000000..f73d047 --- /dev/null +++ b/src/btp/oneP/ChangeSystemOut.java @@ -0,0 +1,14 @@ +package btp.oneP; + +import java.io.PrintWriter; + +public class ChangeSystemOut { + + public static void main(String[] args) { + // TODO Auto-generated method stub + //PrintWriter有接受OutputStream的构造器,将其用OutputStreamWriter转换为Writer + PrintWriter out = new PrintWriter(System.out,true); + out.println("Hello,world"); + } + +} diff --git a/src/btp/oneP/ChannelCopy.java b/src/btp/oneP/ChannelCopy.java new file mode 100644 index 0000000..9805618 --- /dev/null +++ b/src/btp/oneP/ChannelCopy.java @@ -0,0 +1,24 @@ +package btp.oneP; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; + +public class ChannelCopy { + private static final int BSIZE = 1024; + public static void main(String[] args) throws IOException { + FileChannel in = new FileInputStream("C:\\Users\\dell\\Desktop\\IO\\channelIn.txt").getChannel(), + out = new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\channelOut.txt").getChannel(); + ByteBuffer buffer = ByteBuffer.allocate(BSIZE); + while(in.read(buffer) != -1){ + //写完之后:limit = capacity;position = 实际数据大小 + buffer.flip();//limit->position;position->0 + out.write(buffer); + buffer.clear();//limit->capacity;position->0;准备下一路的读 + } + } + +} diff --git a/src/btp/oneP/CollectionSort.java b/src/btp/oneP/CollectionSort.java new file mode 100644 index 0000000..e3426ce --- /dev/null +++ b/src/btp/oneP/CollectionSort.java @@ -0,0 +1,22 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; + +public class CollectionSort { + + public static void main(String[] args) { + Collections.sort(new ArrayList(Arrays.asList(1,2,3,4,5)), new Comparator(){ + + @Override + public int compare(Integer o1, Integer o2) { + return o1 > 02 ? -1 : 1; + } + + }); + + } + +} diff --git a/src/btp/oneP/ConstantSpecificMethod.java b/src/btp/oneP/ConstantSpecificMethod.java new file mode 100644 index 0000000..00587aa --- /dev/null +++ b/src/btp/oneP/ConstantSpecificMethod.java @@ -0,0 +1,37 @@ +package btp.oneP; + +import java.text.DateFormat; +import java.util.Date; + +public enum ConstantSpecificMethod { + DATE_TIME{ + + @Override + String getInfo() { + return DateFormat.getDateInstance().format(new Date()); + } + + }, + cLASSPATH{ + + @Override + String getInfo() { + return System.getenv("CLASSPATH"); + } + + }, + VERSION{ + + @Override + String getInfo() { + return System.getProperty("java.version"); + } + + }; + abstract String getInfo(); + public static void main(String[] args){ + for(ConstantSpecificMethod csm : values()){ + System.out.println(csm.getInfo()); + } + } +} diff --git a/src/btp/oneP/CountedString.java b/src/btp/oneP/CountedString.java new file mode 100644 index 0000000..614a00a --- /dev/null +++ b/src/btp/oneP/CountedString.java @@ -0,0 +1,53 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CountedString { + + private static List created = new ArrayList(); + private String s; + private int id = 0; + public CountedString(String str){ + s = str; + created.add(s); + for(String s2:created){ + if(s2.equals(s)){ + id++; + } + } + } + + public int hashCode(){ + int result = 17; + result = 37*result+s.hashCode(); + result = 37*result+id; + return result; + } + + public boolean equals(Object o){ + return o instanceof CountedString && s.equals(((CountedString)o).s) && id==((CountedString)o).id; + } + + @Override + public String toString() { + return "CountedString [s=" + s + ", id=" + id + "hashCode():"+hashCode()+"]"; + } + + public static void main(String[] args) { + Map map = new HashMap(); + CountedString[] cs = new CountedString[5]; + for(int i=0;i kind){ + values = kind.getEnumConstants(); + } + public Food randomSelection(){ + return Enums.random(values); + } + +} diff --git a/src/btp/oneP/DequeTest.java b/src/btp/oneP/DequeTest.java new file mode 100644 index 0000000..8dbfed1 --- /dev/null +++ b/src/btp/oneP/DequeTest.java @@ -0,0 +1,60 @@ +package btp.oneP; + +import java.util.LinkedList; + +public class DequeTest { + static void fillTest(Deque deque){ + for(int i = 20;i < 27;i++){ + deque.addFirst(i); + } + for(int i = 50;i < 55;i++){ + deque.addLast(i); + } + } + public static void main(String[] args) { + Deque di = new Deque(); + fillTest(di); + System.out.println(di); + + while(di.size() != 0){ + System.out.print(di.removeFirst()+" "); + } + System.out.println(); + + fillTest(di); + while(di.size() != 0){ + System.out.print(di.removeLast()+" "); + } + System.out.println(); + } + +} + + +class Deque{ + private LinkedList deque = new LinkedList(); + public void addFirst(T t){ + deque.add(t); + } + public void addLast(T t){ + deque.addLast(t); + } + public T getFirst(){ + return deque.getFirst(); + } + public T getLast(){ + return deque.getLast(); + } + public T removeFirst(){ + return deque.removeFirst(); + } + public T removeLast(){ + return deque.removeLast(); + } + public int size(){ + return deque.size(); + } + public String toString(){ + return deque.toString(); + } +} \ No newline at end of file diff --git a/src/btp/oneP/DirList.java b/src/btp/oneP/DirList.java new file mode 100644 index 0000000..6c533c9 --- /dev/null +++ b/src/btp/oneP/DirList.java @@ -0,0 +1,38 @@ +package btp.oneP; + +import java.io.File; +import java.io.FilenameFilter; +import java.util.Arrays; +import java.util.regex.Pattern; + +public class DirList { + + public static void main(String[] args) { + File path = new File("E:\\workspaces\\NewWork\\Study\\src\\btp\\oneP"); + String[] list; + if(args.length == 0){ + list = path.list(); + }else{ + list = path.list(new DirFilter(args[0])); + } + Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); + for(String dirItem : list){ + System.out.println(dirItem); + } + } + +} + +class DirFilter implements FilenameFilter{ + private Pattern pattern; + + public DirFilter(String regex){ + pattern = Pattern.compile(regex); + } + @Override + public boolean accept(File dir, String name) { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/src/btp/oneP/DirList2.java b/src/btp/oneP/DirList2.java new file mode 100644 index 0000000..c79ef18 --- /dev/null +++ b/src/btp/oneP/DirList2.java @@ -0,0 +1,43 @@ +package btp.oneP; + +import java.io.File; +import java.io.FilenameFilter; +import java.util.Arrays; +import java.util.regex.Pattern; + +public class DirList2 { + public static FilenameFilter filter(final String regex){ + return new FilenameFilter(){ + private Pattern pattern = Pattern.compile(regex); + @Override + public boolean accept(File dir, String name) { + // TODO Auto-generated method stub + return pattern.matcher(name).matches(); + } + + }; + } + public static void main(final String[] args) { + File path = new File("E:\\workspaces\\NewWork\\Study\\src\\btp\\oneP"); + String[] list; + if(args.length == 0){ + list = path.list(); + }else{ + //list = path.list(filter(args[0])); + list = path.list(new FilenameFilter(){ + private Pattern pattern = Pattern.compile(args[0]); + @Override + public boolean accept(File dir, String name) { + // TODO Auto-generated method stub + return pattern.matcher(name).matches(); + } + + }); + } + Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); + for(String dirItem : list){ + System.out.println(dirItem); + } + } + +} diff --git a/src/btp/oneP/Directory.java b/src/btp/oneP/Directory.java new file mode 100644 index 0000000..512decb --- /dev/null +++ b/src/btp/oneP/Directory.java @@ -0,0 +1,82 @@ +package btp.oneP; + +import java.io.File; +import java.io.FilenameFilter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.regex.Pattern; + +public class Directory { + public static File[] local(File dir,final String regex){ + return dir.listFiles(new FilenameFilter(){ + private Pattern pattern = Pattern.compile(regex); + @Override + public boolean accept(File dir, String name) { + return pattern.matcher(new File(name).getName()).matches(); + } + + }); + } + + public static File[] local(String path,final String regex){ + return local(new File(path),regex); + } + + public static class TreeInfo implements Iterable{ + public List files = new ArrayList(); + public List dirs = new ArrayList(); + @Override + public Iterator iterator() { + // TODO Auto-generated method stub + return files.iterator(); + } + + void addAll(TreeInfo other){ + files.addAll(other.files); + dirs.addAll(other.dirs); + } + public String toString(){ + StringBuilder sb = new StringBuilder(); + sb.append("dirs: \n"); + for(File f : dirs){ + sb.append(f.getPath()+"\n"); + } + sb.append("files: \n"); + for(File f : files){ + sb.append(f.getPath()+"\n"); + } + return sb.toString(); + } + } + + public static TreeInfo walk(String start,String regex){ + return recurseDirs(new File(start),regex); + } + public static TreeInfo walk(File start,String regex){ + return recurseDirs(start,regex); + } + public static TreeInfo walk(File start){ + return recurseDirs(start,".*"); + } + public static TreeInfo walk(String start){ + return recurseDirs(new File(start),".*"); + } + + private static TreeInfo recurseDirs(File file, String regex) { + TreeInfo result = new TreeInfo(); + for(File item : file.listFiles()){ + if(item.isDirectory()){ + result.dirs.add(item); + result.addAll(recurseDirs(item,regex)); + }else{ + if(item.getName().matches(regex)) + result.files.add(item); + } + } + return result; + } + public static void main(String...args){ + System.out.println(walk("C:\\Users\\dell\\Desktop\\pdf.js")); + } +} diff --git a/src/btp/oneP/DirectoryDemo.java b/src/btp/oneP/DirectoryDemo.java new file mode 100644 index 0000000..1357839 --- /dev/null +++ b/src/btp/oneP/DirectoryDemo.java @@ -0,0 +1,32 @@ +package btp.oneP; + +import java.io.File; +import java.io.IOException; + +public class DirectoryDemo { + + public static void main(String[] args) throws IOException { + PPrint.pprint(Directory.walk(".").dirs); + for(File file : Directory.local(".", "T.*")){ + System.out.println(file); + } + System.out.println("---------------------"); + for(File file : Directory.local(".", "T.*\\.java")){ + System.out.println(file); + } + System.out.println("====================="); + for(File file : Directory.local(".", ".*[Zz].*\\.class")){ + System.out.println(file); + } + + File file = new File("C:\\Users\\dell\\Desktop\\pdf.js\\build.zip"); + file = new File(""); + System.out.println(file.getAbsolutePath()); + System.out.println(file.getCanonicalPath()); + System.out.println(System.getProperty("user.dir")); + System.out.println(System.getProperty("os.name")); + System.out.println(System.getProperty("os.arch")); + System.out.println(System.getenv()); + } + +} diff --git a/src/btp/oneP/Echo.java b/src/btp/oneP/Echo.java new file mode 100644 index 0000000..618fce8 --- /dev/null +++ b/src/btp/oneP/Echo.java @@ -0,0 +1,17 @@ +package btp.oneP; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Echo { + + public static void main(String[] args) throws IOException { + BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); + String s; + while((s = stdin.readLine()) != null && s.length() != 0){ + System.out.println(s.toUpperCase()); + } + } + +} diff --git a/src/btp/oneP/Element.java b/src/btp/oneP/Element.java new file mode 100644 index 0000000..f2f1467 --- /dev/null +++ b/src/btp/oneP/Element.java @@ -0,0 +1,20 @@ +package btp.oneP; + +public class Element { + private String ident; + public Element(String id){ + ident = id; + } + public String toString(){ + return ident; + } + public int hashCode(){ + return ident.hashCode(); + } + public boolean equals(Object r){ + return r instanceof Element && ident.equals(((Element)r).ident); + } + protected void finalize(){ + System.out.println("Finalizing "+this.getClass().getSimpleName()+" "+ident+":"+(Integer.parseInt(ident)%3==0)); + } +} diff --git a/src/btp/oneP/Endians.java b/src/btp/oneP/Endians.java new file mode 100644 index 0000000..87a6d1d --- /dev/null +++ b/src/btp/oneP/Endians.java @@ -0,0 +1,23 @@ +package btp.oneP; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Arrays; + +public class Endians { + + public static void main(String[] args) { + ByteBuffer bb = ByteBuffer.wrap(new byte[12]); + bb.asCharBuffer().put("abcdef"); + System.out.println(Arrays.toString(bb.array())); + bb.rewind(); + bb.order(ByteOrder.BIG_ENDIAN); + bb.asCharBuffer().put("abcdef"); + System.out.println(Arrays.toString(bb.array())); + bb.rewind(); + bb.order(ByteOrder.LITTLE_ENDIAN); + bb.asCharBuffer().put("abcdef"); + System.out.println(Arrays.toString(bb.array())); + } + +} diff --git a/src/btp/oneP/EnumClass.java b/src/btp/oneP/EnumClass.java new file mode 100644 index 0000000..e032f41 --- /dev/null +++ b/src/btp/oneP/EnumClass.java @@ -0,0 +1,25 @@ +package btp.oneP; + +public class EnumClass { + + public static void main(String[] args) { + for(Shrubbery s : Shrubbery.values()){ + System.out.println(s + " ordinal:" + s.ordinal()); + System.out.println(s.compareTo(Shrubbery.CRAELING)); + System.out.println(s.equals(Shrubbery.CRAELING)); + System.out.println(s == Shrubbery.CRAELING); + System.out.println(s.getDeclaringClass()); + System.out.println(s.name()); + System.out.println("--------------------"); + } + for(String s : "HANGING CRAELING GROUND".split(" ")){ + Shrubbery shurb = Enum.valueOf(Shrubbery.class, s); + System.out.println(shurb); + } + } + +} + +enum Shrubbery{ + GROUND,CRAELING,HANGING; +} diff --git a/src/btp/oneP/EnumImplementation.java b/src/btp/oneP/EnumImplementation.java new file mode 100644 index 0000000..cce588a --- /dev/null +++ b/src/btp/oneP/EnumImplementation.java @@ -0,0 +1,26 @@ +package btp.oneP; + +import java.util.Random; + +public class EnumImplementation { + public static void printNext(GeneratorN rg){ + System.out.println(rg.next() + ", "); + } + public static void main(String[] args) { + CartoonCharacter cc = CartoonCharacter.BOB; + for(int i = 0;i<10;i++){ + printNext(cc); + } + } + +} + +enum CartoonCharacter implements GeneratorN{ + SLAPPY,SPANKY,PUNCHY,SILLY,BOUNCY,NUTTY,BOB; + private Random rand = new Random(47); + @Override + public CartoonCharacter next() { + return values()[rand.nextInt(values().length)]; + } + +} diff --git a/src/btp/oneP/EnumMaps.java b/src/btp/oneP/EnumMaps.java new file mode 100644 index 0000000..c006f97 --- /dev/null +++ b/src/btp/oneP/EnumMaps.java @@ -0,0 +1,60 @@ +package btp.oneP; + +import java.util.EnumMap; +import java.util.Map; + +public class EnumMaps { + + public static void main(String[] args) { + EnumMap em = + new EnumMap(AlarmPoints.class); + em.put(AlarmPoints.KITCHEN, new CommandI(){ + + @Override + public void action() { + System.out.print("Kitchen fire!"); + } + + }); + em.put(AlarmPoints.BATHROOM, new CommandI(){ + + @Override + public void action() { + System.out.print("Bathroom alert!"); + } + + }); + em.put(AlarmPoints.LOBBY, new CommandI(){ + + @Override + public void action() { + System.out.print("LOBBY fire!"); + } + + }); + em.put(AlarmPoints.OFFICE1, new CommandI(){ + + @Override + public void action() { + System.out.print("office1 fire!"); + } + + }); + + for(Map.Entry e : em.entrySet()){ + System.out.print(e.getKey() + ": "); + e.getValue().action(); + System.out.println(); + } + try{ + em.get(AlarmPoints.UTILITY).action(); + }catch(Exception e){ + e.printStackTrace(); + } + } + +} + +interface CommandI{ + void action(); +} \ No newline at end of file diff --git a/src/btp/oneP/EnumSets.java b/src/btp/oneP/EnumSets.java new file mode 100644 index 0000000..0adede5 --- /dev/null +++ b/src/btp/oneP/EnumSets.java @@ -0,0 +1,30 @@ +package btp.oneP; + +import java.util.EnumSet; + +public class EnumSets { + + public static void main(String[] args) { + EnumSet points = EnumSet.noneOf(AlarmPoints.class); + points.add(AlarmPoints.BATHROOM); + System.out.println(points); + points.addAll(EnumSet.of(AlarmPoints.START1, AlarmPoints.START2, AlarmPoints.KITCHEN)); + System.out.println(points); + points = EnumSet.allOf(AlarmPoints.class); + points.removeAll(EnumSet.of(AlarmPoints.START1, AlarmPoints.START2, AlarmPoints.KITCHEN)); + System.out.println(points); + points.removeAll(EnumSet.range(AlarmPoints.OFFICE1, AlarmPoints.OFFICE4)); + System.out.println(points); + points = EnumSet.complementOf(points); + System.out.println(points); + points = EnumSet.complementOf(EnumSet.allOf(AlarmPoints.class)); + System.out.println(points); + points = EnumSet.complementOf(EnumSet.noneOf(AlarmPoints.class)); + System.out.println(points); + } + +} + +enum AlarmPoints{ + START1,START2,LOBBY,OFFICE1,OFFICE2,OFFICE3,OFFICE4,BATHROOM,UTILITY,KITCHEN +} diff --git a/src/btp/oneP/Enumerations.java b/src/btp/oneP/Enumerations.java new file mode 100644 index 0000000..5fb98dd --- /dev/null +++ b/src/btp/oneP/Enumerations.java @@ -0,0 +1,20 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.Vector; + +public class Enumerations { + + public static void main(String[] args) { + Vector v = new Vector(Countries.names(10)); + Enumeration e = v.elements(); + while(e.hasMoreElements()){ + System.out.println(e.nextElement()+", "); + } + e = Collections.enumeration(new ArrayList()); + + } + +} diff --git a/src/btp/oneP/Enums.java b/src/btp/oneP/Enums.java new file mode 100644 index 0000000..6c1381e --- /dev/null +++ b/src/btp/oneP/Enums.java @@ -0,0 +1,13 @@ +package btp.oneP; + +import java.util.Random; + +public class Enums { + private static Random rand = new Random(47); + public static > T random(Class ec){ + return random(ec.getEnumConstants()); + } + public static T random(T[] values){ + return values[rand.nextInt(values.length)]; + } +} diff --git a/src/btp/oneP/FailFast.java b/src/btp/oneP/FailFast.java new file mode 100644 index 0000000..604e610 --- /dev/null +++ b/src/btp/oneP/FailFast.java @@ -0,0 +1,21 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.ConcurrentModificationException; +import java.util.Iterator; + +public class FailFast { + + public static void main(String[] args) { + Collection c = new ArrayList(); + Iterator it = c.iterator(); + c.add("An object"); + try{ + String s = it.next(); + }catch(ConcurrentModificationException e){ + System.out.println(e); + } + } + +} diff --git a/src/btp/oneP/FileLocking.java b/src/btp/oneP/FileLocking.java new file mode 100644 index 0000000..402652c --- /dev/null +++ b/src/btp/oneP/FileLocking.java @@ -0,0 +1,22 @@ +package btp.oneP; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.channels.FileLock; +import java.util.concurrent.TimeUnit; + +public class FileLocking { + + public static void main(String[] args) throws IOException, InterruptedException { + FileOutputStream fos = new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\file.txt"); + FileLock fl = fos.getChannel().tryLock(); + if(null != fl){ + System.out.println("Locked File"); + TimeUnit.MICROSECONDS.sleep(100); + fl.release(); + System.out.println("Released Lock"); + } + fos.close(); + } + +} diff --git a/src/btp/oneP/FileOutputShortcut.java b/src/btp/oneP/FileOutputShortcut.java new file mode 100644 index 0000000..9392ebd --- /dev/null +++ b/src/btp/oneP/FileOutputShortcut.java @@ -0,0 +1,25 @@ +package btp.oneP; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; + +public class FileOutputShortcut { + + static String file = "C:\\Users\\dell\\Desktop\\IO\\io.txt"; + public static void main(String[] args) throws IOException { + BufferedReader in = new BufferedReader(new StringReader(BufferedInputFile.read("E:\\workspaces\\NewWork\\Study\\src\\btp\\oneP\\FileOutputShortcut.java"))); + PrintWriter out = new PrintWriter(file); + int lineCount = 1; + String s; + while((s = in.readLine()) != null){ + out.println(lineCount++ + " : " + s); + } + out.close(); + System.out.println(BufferedInputFile.read(file)); + } + +} diff --git a/src/btp/oneP/Food.java b/src/btp/oneP/Food.java new file mode 100644 index 0000000..ab8e76d --- /dev/null +++ b/src/btp/oneP/Food.java @@ -0,0 +1,16 @@ +package btp.oneP; + +public interface Food { + enum Appetizer implements Food{ + SALAD,SOUP,SPRING_ROLLS; + } + enum MainCourse implements Food{ + LASAGNE,BURRITO,PAD_THAI,LENTILS,HUMMOUS,VINDALOO; + } + enum DESSERT implements Food{ + TIRAMISU,GELATO,BLACK_FOREST_CAKE,FRUIT,CREME_CARAMEL; + } + enum Coffee implements Food{ + BLACK_COFFEE,DECAF_COFFEE,ESPRESSO,LATTE,CAPPUCCINO,TEA,HERB_TEA; + } +} diff --git a/src/btp/oneP/FormattedMemoryInput.java b/src/btp/oneP/FormattedMemoryInput.java new file mode 100644 index 0000000..b4289cb --- /dev/null +++ b/src/btp/oneP/FormattedMemoryInput.java @@ -0,0 +1,22 @@ +package btp.oneP; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.EOFException; +import java.io.IOException; + +public class FormattedMemoryInput { + + public static void main(String[] args) throws IOException { + // TODO Auto-generated method stub + try{ + DataInputStream in = new DataInputStream(new ByteArrayInputStream(BufferedInputFile.read("E:\\workspaces\\NewWork\\Study\\src\\btp\\oneP\\FormattedMemoryInput.java").getBytes())); + while(true){ + System.out.print((char)in.readByte()); + } + }catch(EOFException e){ + System.out.println("End of stream"); + } + } + +} diff --git a/src/btp/oneP/GZIPcompress.java b/src/btp/oneP/GZIPcompress.java new file mode 100644 index 0000000..f8e3edf --- /dev/null +++ b/src/btp/oneP/GZIPcompress.java @@ -0,0 +1,34 @@ +package btp.oneP; + +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +public class GZIPcompress { + + public static void main(String[] args) throws IOException { + BufferedReader in = new BufferedReader(new FileReader(new File("C:\\Users\\dell\\Desktop\\IO\\test2.txt"))); + BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\test2.gz"))); + System.out.println("Writing file"); + int c; + while((c = in.read()) != -1){ + out.write(c); + } + in.close(); + out.close(); + System.out.println("Reading file"); + BufferedReader in2 = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("C:\\Users\\dell\\Desktop\\IO\\test2.gz")))); + String s; + while((s = in2.readLine()) != null){ + System.out.println(s); + } + } + +} diff --git a/src/btp/oneP/GetChannel.java b/src/btp/oneP/GetChannel.java new file mode 100644 index 0000000..195cf0e --- /dev/null +++ b/src/btp/oneP/GetChannel.java @@ -0,0 +1,30 @@ +package btp.oneP; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; + +public class GetChannel { + private static final int BSIZE = 1024; + @SuppressWarnings("resource") + public static void main(String...args) throws IOException{ + FileChannel fc = new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\test.out").getChannel(); + fc.write(ByteBuffer.wrap("Some test".getBytes())); + fc.close(); + fc = new RandomAccessFile("C:\\Users\\dell\\Desktop\\IO\\test.out","rw").getChannel(); + fc.position(fc.size()); + fc.write(ByteBuffer.wrap("Some more".getBytes())); + fc.close(); + fc = new FileInputStream("C:\\Users\\dell\\Desktop\\IO\\test.out").getChannel(); + ByteBuffer buff = ByteBuffer.allocate(BSIZE); + fc.read(buff); + //把limit设置为position的值,position设置为0 + buff.flip(); + while(buff.hasRemaining()){ + System.out.print((char)buff.get()); + } + } +} diff --git a/src/btp/oneP/GetData.java b/src/btp/oneP/GetData.java new file mode 100644 index 0000000..be26ea4 --- /dev/null +++ b/src/btp/oneP/GetData.java @@ -0,0 +1,46 @@ +package btp.oneP; + +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +public class GetData { + private static final int BSIZE = 1024; + public static void main(String[] args) { + ByteBuffer bb = ByteBuffer.allocate(BSIZE); + int i = 0; + System.out.println(bb.limit()); + while(i++ < bb.limit()){ + if(bb.get() != 0){ + System.out.print("nonzero"); + } + } + System.out.println("i = "+i); + bb.rewind(); + bb.asCharBuffer().put("Howdy"); + char c; + while((c = bb.getChar()) != 0){ + System.out.print(c+" "); + } + bb.rewind(); + bb.asShortBuffer().put((short)471142); + System.out.println(bb.getShort()); + bb.rewind(); + bb.asIntBuffer().put(99471142); + System.out.print(bb.getInt()); + + System.out.println(Charset.forName(System.getProperty("file.encoding")).decode(bb)); + bb.rewind(); + bb.asLongBuffer().put(99471142); + System.out.println(bb.getLong()); + bb.rewind(); + System.out.println(Charset.forName(System.getProperty("file.encoding")).decode(bb)); + bb.rewind(); + bb.asFloatBuffer().put(99471142); + System.out.println(bb.getFloat()); + bb.rewind(); + bb.asDoubleBuffer().put(99471142); + System.out.println(bb.getDouble()); + bb.rewind(); + } + +} diff --git a/src/btp/oneP/Individual.java b/src/btp/oneP/Individual.java new file mode 100644 index 0000000..fb20acf --- /dev/null +++ b/src/btp/oneP/Individual.java @@ -0,0 +1,48 @@ +package btp.oneP; + +public class Individual implements Comparable { + private static long counter = 0; + private final long id = counter++; + private String name; + public Individual(String name){ + this.name = name; + } + public Individual(){} + public String toString(){ + return this.getClass().getSimpleName()+(name == null?"":" "+name); + } + public long id(){ + return id; + } + public boolean equals(Object o){ + return o instanceof Individual && id == ((Individual)o).id; + } + public int hashCode(){ + int result = 17; + if(name != null){ + result = 37*result+name.hashCode(); + } + result = 37*result+(int)id; + return result; + } + @Override + public int compareTo(Individual o) { + String first = getClass().getSimpleName(); + String argFirst = o.getClass().getSimpleName(); + int firstCompare = first.compareTo(argFirst); + if(0 != firstCompare){ + return firstCompare; + } + if(name != null && o.name != null){ + int secondCompare = name.compareTo(o.name); + if(secondCompare != 0){ + return secondCompare; + } + } + return (o.id linkedMap = new LinkedHashMap(new CountingMapData(9)); + System.out.println(linkedMap); + //false:基于插入顺序 true:基于访问顺序 LRU:最近最少访问,默认是false + linkedMap = new LinkedHashMap(16,0.75f,true); + linkedMap.putAll(new CountingMapData(9)); + System.out.println(linkedMap); + for(int i = 0;i<6;i++){ + linkedMap.get(i); + } + System.out.println(linkedMap); + linkedMap.get(0); + System.out.println(linkedMap); + } + +} diff --git a/src/btp/oneP/ListPerformance.java b/src/btp/oneP/ListPerformance.java new file mode 100644 index 0000000..4024bd4 --- /dev/null +++ b/src/btp/oneP/ListPerformance.java @@ -0,0 +1,188 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; +import java.util.Random; + +import javax.annotation.Generated; + +public class ListPerformance { + + static Random rand = new Random(); + static int reps = 1000; + static List>> tests = new ArrayList>>(); + static List>> qTests = new ArrayList>>(); + + static{ + tests.add(new TestCollection>("add"){ + @Override + int test(List list, TestParam tp) { + int loops = tp.loops; + int listSize = tp.size; + for(int i=0;i>("get"){ + @Override + int test(List list, TestParam tp) { + int loops = tp.loops * reps; + int listSize = list.size(); + for(int i=0;i>("set"){ + @Override + int test(List list, TestParam tp) { + int loops = tp.loops * reps; + int listSize = list.size(); + for(int i=0;i>("iteradd"){ + @Override + int test(List list, TestParam tp) { + final int LOOPS = 1000000; + int half = list.size()/2; + ListIterator it = list.listIterator(half); + for(int i=0;i>("insert"){ + @Override + int test(List list, TestParam tp) { + int loops = tp.loops; + for(int i=0;i>("remove"){ + @Override + int test(List list, TestParam tp) { + int loops = tp.loops; + int size = tp.size; + for(int i=0;i 5){ + list.remove(5); + } + } + return loops*size; + } + }); + + qTests.add(new TestCollection>("addFirst"){ + @Override + int test(LinkedList list, TestParam tp) { + int loops = tp.loops; + int size = tp.size; + for(int i=0;i>("addLast"){ + @Override + int test(LinkedList list, TestParam tp) { + int loops = tp.loops; + int size = tp.size; + for(int i=0;i>("rmFirst"){ + @Override + int test(LinkedList list, TestParam tp) { + int loops = tp.loops; + int size = tp.size; + for(int i=0;i0){ + list.removeFirst(); + } + } + return loops * size; + } + }); + + qTests.add(new TestCollection>("rmLast"){ + @Override + int test(LinkedList list, TestParam tp) { + int loops = tp.loops; + int size = tp.size; + for(int i=0;i0){ + list.removeLast(); + } + } + return loops * size; + } + }); + } + + static class ListTester extends Tester>{ + + public ListTester(List container, List>> tests) { + super(container, tests); + // TODO Auto-generated constructor stub + } + + protected List initialize(int size){ + container.clear(); + container.addAll(new CountingIntegerList(size)); + return container; + } + + public static void run(List list, List>> tests){ + new ListTester(list,tests).timedTest(); + } + } + public static void main(String[] args) { + if(args.length > 0){ + Tester.defaultParams = TestParam.array(args); + Tester> arrayTest = new Tester>(null,tests.subList(1, 3)){ + + }; + } + } + +} diff --git a/src/btp/oneP/ListSortSearch.java b/src/btp/oneP/ListSortSearch.java new file mode 100644 index 0000000..e31b5d6 --- /dev/null +++ b/src/btp/oneP/ListSortSearch.java @@ -0,0 +1,39 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.ListIterator; +import java.util.Random; + +public class ListSortSearch { + + public static void main(String[] args) { + List list = new ArrayList(Utilities.list); + list.addAll(Utilities.list); + System.out.println(list); + Collections.shuffle(list,new Random(47)); + System.out.println("Shuffled:"+list); + ListIterator it = list.listIterator(10); + while(it.hasNext()){ + System.out.print(it.next()+" "); + it.remove(); + } + System.out.println(); + System.out.println("Trimmed:"+list); + Collections.sort(list); + System.out.println("Sorted:"+list); + + String key = list.get(7); + int index = Collections.binarySearch(list, key); + System.out.println("Location of "+key+" is "+index+",list.get("+index+") = "+list.get(index)); + + Collections.sort(list, String.CASE_INSENSITIVE_ORDER); + System.out.println("Case-insensitive soretd:"+list); + key = list.get(7); + index = Collections.binarySearch(list, key,String.CASE_INSENSITIVE_ORDER); + System.out.println("Location of "+key+" is "+index+",list.get("+index+") = "+list.get(index)); + + } + +} diff --git a/src/btp/oneP/LockingMappedFiles.java b/src/btp/oneP/LockingMappedFiles.java new file mode 100644 index 0000000..c57a2dd --- /dev/null +++ b/src/btp/oneP/LockingMappedFiles.java @@ -0,0 +1,50 @@ +package btp.oneP; + +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; + +public class LockingMappedFiles { + static final int LENGTH = 0x8FFFFFF;//128MB + static FileChannel fc; + @SuppressWarnings("resource") + public static void main(String[] args) throws IOException { + fc = new RandomAccessFile("C:\\Users\\dell\\Desktop\\IO\\test.dat","rw").getChannel(); + MappedByteBuffer out = fc.map(FileChannel.MapMode.READ_WRITE, 0, LENGTH); + for(int i = 0;i implements Map.Entry{ + private K key; + private V value; + public MapEntry(K key,V value){ + this.key = key; + this.value = value; + } + @Override + public K getKey() { + // TODO Auto-generated method stub + return key; + } + + @Override + public V getValue() { + return value; + } + + @Override + public V setValue(V value) { + //返回的不是类的属性 + V result = value; + this.value = value; + return result; + } + + public int hashCode(){ + return (key == null ? 0 :key.hashCode()) ^ (value == null ? 0 :value.hashCode()); + } + + public boolean equals(Object o){ + if(!(o instanceof MapEntry)) return false; + MapEntry me = (MapEntry)o; + return + (key == null?me.getKey() == null:key.equals(me.getKey())) + && + (value == null?me.getValue() == null:value.equals(me.getValue())); + } + + public String toString(){ + return key+"="+value; + } +} diff --git a/src/btp/oneP/MappedIO.java b/src/btp/oneP/MappedIO.java new file mode 100644 index 0000000..c52d647 --- /dev/null +++ b/src/btp/oneP/MappedIO.java @@ -0,0 +1,118 @@ +package btp.oneP; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.IntBuffer; +import java.nio.channels.FileChannel; + +public class MappedIO { + private static int numOfInts = 4000000; + private static int numOfUbuffInts = 200000; + private abstract static class Tester{ + private String name; + public Tester(String name){ + this.name = name; + } + public void runTest(){ + System.out.println(name + ": "); + try{ + long start = System.nanoTime(); + test(); + double duration = System.nanoTime() - start; + System.out.format("%.2f\n", duration/1.0e9); + }catch(IOException e){ + throw new RuntimeException(e); + } + } + public abstract void test() throws IOException; + } + private static Tester[] tests= { + new Tester("Stream Write"){ + + @Override + public void test() throws IOException { + DataOutputStream dos = new DataOutputStream( + new BufferedOutputStream(new FileOutputStream(new File("temp.tmp")))); + for(int i = 0;i < numOfInts; i++){ + dos.writeInt(i); + } + dos.close(); + } + }, + new Tester("Mapped Write"){ + + @Override + public void test() throws IOException { + FileChannel fc = new RandomAccessFile("temp.tmp","rw").getChannel(); + IntBuffer ib = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size()).asIntBuffer(); + for(int i = 0;i < numOfInts;i++){ + ib.put(i); + } + fc.close(); + } + }, + new Tester("Stream Read"){ + + @Override + public void test() throws IOException { + DataInputStream dis = new DataInputStream( + new BufferedInputStream(new FileInputStream(new File("temp.tmp")))); + for(int i = 0;i < numOfInts; i++){ + dis.readInt(); + } + dis.close(); + } + }, + new Tester("Mapped Read"){ + + @Override + public void test() throws IOException { + FileChannel fc = new FileInputStream(new File("temp.tmp")).getChannel(); + IntBuffer ib = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()).asIntBuffer(); + while(ib.hasRemaining()){ + ib.get(); + } + fc.close(); + } + }, + new Tester("Stream Read/Write"){ + + @Override + public void test() throws IOException { + RandomAccessFile raf = new RandomAccessFile(new File("temp.tmp"),"rw"); + raf.writeInt(1); + for(int i = 0;i()); + test(new TreeMap()); + test(new LinkedHashMap()); + test(new IdentityHashMap()); + test(new ConcurrentHashMap()); + test(new WeakHashMap()); + } + public static void printKeys(Map map){ + System.out.print("Size = "+map.size()+","); + System.out.println("Keys: "); + System.out.println(map.keySet()); + } + + public static void test(Map map){ + System.out.println(map.getClass().getSimpleName()); + map.putAll(new CountingMapData(25)); + map.putAll(new CountingMapData(25)); + printKeys(map); + System.out.println("Values: "); + System.out.println(map.values()); + System.out.println(map); + System.out.println("map.containsKey(11):"+map.containsKey(11)); + System.out.println("map.get(11):"+map.get(11)); + System.out.println("map.containsValue(\"F0\"):"+map.containsValue("F0")); + Integer key = map.keySet().iterator().next(); + System.out.println("First key in map:"+key); + map.remove(key); + printKeys(map); + map.clear(); + System.out.println("map.isEmpty():"+map.isEmpty()); + map.putAll(new CountingMapData(25)); + map.keySet().removeAll(map.keySet()); + System.out.println("map.isEmpty():"+map.isEmpty()); + System.out.println("---------------"); + } +} diff --git a/src/btp/oneP/Meal.java b/src/btp/oneP/Meal.java new file mode 100644 index 0000000..4fd58fc --- /dev/null +++ b/src/btp/oneP/Meal.java @@ -0,0 +1,15 @@ +package btp.oneP; + +public class Meal { + + public static void main(String[] args) { + for(int i = 0; i < 5; i ++){ + for(Course course : Course.values()){ + Food food = course.randomSelection(); + System.out.println(food); + } + System.out.println("---"); + } + } + +} diff --git a/src/btp/oneP/MemoryInput.java b/src/btp/oneP/MemoryInput.java new file mode 100644 index 0000000..6b10db7 --- /dev/null +++ b/src/btp/oneP/MemoryInput.java @@ -0,0 +1,16 @@ +package btp.oneP; + +import java.io.IOException; +import java.io.StringReader; + +public class MemoryInput { + + public static void main(String[] args) throws IOException { + StringReader im = new StringReader(BufferedInputFile.read("E:\\workspaces\\NewWork\\Study\\src\\btp\\oneP\\MemoryInput.java")); + int c; + while((c = im.read()) != -1){ + System.out.print((char)c); + } + } + +} diff --git a/src/btp/oneP/MyWorld.java b/src/btp/oneP/MyWorld.java new file mode 100644 index 0000000..40d630b --- /dev/null +++ b/src/btp/oneP/MyWorld.java @@ -0,0 +1,77 @@ +package btp.oneP; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class MyWorld { + + public static void main(String[] args) throws IOException, ClassNotFoundException { + House house = new House(); + List animals = new ArrayList(); + animals.add(new Animal("Bosco the dog",house)); + animals.add(new Animal("Ralph the hamster",house)); + animals.add(new Animal("Molly the cat",house)); + System.out.println("animals:"+animals); + ByteArrayOutputStream buf1 = new ByteArrayOutputStream(); + ObjectOutputStream o1 = new ObjectOutputStream(buf1); + o1.writeObject(animals); + o1.writeObject(animals); + ByteArrayOutputStream buf2 = new ByteArrayOutputStream(); + ObjectOutputStream o2 = new ObjectOutputStream(buf2); + o2.writeObject(animals); + ObjectInputStream in1 = new ObjectInputStream(new ByteArrayInputStream(buf1.toByteArray())); + ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(buf2.toByteArray())); + List animals1 = (List) in1.readObject(); + System.out.println("animals1:"+animals1); + House h2 = new House(); + System.out.println(h2); + for(Object an:animals1){ + ((Animal)an).setPreferredHouse(h2); + } + List animals2 = (List) in1.readObject(); + List animals3 = (List) in2.readObject(); + System.out.println("animals1: "+animals1); + System.out.println("animals2: "+animals2); + System.out.println("animals3: "+animals3); + } + +} + +class House implements Serializable{ + +} + +class Animal implements Serializable{ + private String name; + private House preferredHouse; + Animal(String nm,House h){ + name = nm; + preferredHouse = h; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public House getPreferredHouse() { + return preferredHouse; + } + + public void setPreferredHouse(House preferredHouse) { + this.preferredHouse = preferredHouse; + } + + public String toString(){ + return name+"["+super.toString()+"],"+preferredHouse+"\n"; + } +} diff --git a/src/btp/oneP/OSExecute.java b/src/btp/oneP/OSExecute.java new file mode 100644 index 0000000..bc5e74d --- /dev/null +++ b/src/btp/oneP/OSExecute.java @@ -0,0 +1,32 @@ +package btp.oneP; + +import java.io.BufferedReader; +import java.io.InputStreamReader; + +public class OSExecute { + public static void command(String command){ + boolean err = false; + try{ + Process process = new ProcessBuilder(command.split(" ")).start(); + BufferedReader results = new BufferedReader(new InputStreamReader(process.getInputStream())); + String s; + while((s = results.readLine()) != null){ + System.out.println(s); + } + BufferedReader errors = new BufferedReader(new InputStreamReader(process.getErrorStream())); + while((s = errors.readLine()) != null){ + System.out.println(s); + err = true; + } + }catch(Exception e){ + if(!command.startsWith("CMD /C")){ + command("CMD /C "+command); + }else{ + throw new RuntimeException(e); + } + } + if(err){ + throw new OSExecuteException("Errors executeing "+command); + } + } +} diff --git a/src/btp/oneP/OSExecuteDemo.java b/src/btp/oneP/OSExecuteDemo.java new file mode 100644 index 0000000..bf461bc --- /dev/null +++ b/src/btp/oneP/OSExecuteDemo.java @@ -0,0 +1,9 @@ +package btp.oneP; + +public class OSExecuteDemo { + + public static void main(String[] args) { + OSExecute.command("javap OSExecuteDemo"); + } + +} diff --git a/src/btp/oneP/OSExecuteException.java b/src/btp/oneP/OSExecuteException.java new file mode 100644 index 0000000..0908b61 --- /dev/null +++ b/src/btp/oneP/OSExecuteException.java @@ -0,0 +1,7 @@ +package btp.oneP; + +public class OSExecuteException extends RuntimeException{ + public OSExecuteException(String why){ + super(why); + } +} diff --git a/src/btp/oneP/OverrideConstantSpecific.java b/src/btp/oneP/OverrideConstantSpecific.java new file mode 100644 index 0000000..86279ad --- /dev/null +++ b/src/btp/oneP/OverrideConstantSpecific.java @@ -0,0 +1,19 @@ +package btp.oneP; + +public enum OverrideConstantSpecific { + NUT,BOLT, + WASHER{ + void f(){ + System.out.println("Overridden method"); + } + }; + void f(){ + System.out.println("default behavior"); + } + public static void main(String...args){ + for(OverrideConstantSpecific ocs : values()){ + System.out.print(ocs + ": "); + ocs.f(); + } + } +} diff --git a/src/btp/oneP/OzWitch.java b/src/btp/oneP/OzWitch.java new file mode 100644 index 0000000..4897353 --- /dev/null +++ b/src/btp/oneP/OzWitch.java @@ -0,0 +1,23 @@ +package btp.oneP; + +public enum OzWitch { + WEST("Miss Gulch,aka the Wicked Witch of the West"), + NORTH("Glinda,the Good Witch of the North"), + EAST("Slippers,crushed by Dorothy's house"), + SOUTH("Good by inference,but missing"); + + private String description; + private OzWitch(String description){ + this.description = description; + } + + public String getDescription(){ + return this.description; + } + public static void main(String...args){ + for(OzWitch witch : OzWitch.values()){ + System.out.println(witch + ": "+witch.getDescription()); + } + + } +} diff --git a/src/btp/oneP/PPrint.java b/src/btp/oneP/PPrint.java new file mode 100644 index 0000000..93bf6d6 --- /dev/null +++ b/src/btp/oneP/PPrint.java @@ -0,0 +1,30 @@ +package btp.oneP; + +import java.util.Arrays; +import java.util.Collection; + +public class PPrint { + public static String pformat(Collection c){ + if(c.size() == 0) return "[]"; + StringBuilder result = new StringBuilder("["); + for(Object elem : c){ + if(c.size() != 1){ + result.append("\n "); + } + result.append(elem); + } + if(c.size() != 1){ + result.append("\n"); + } + result.append("]"); + return result.toString(); + } + + public static void pprint(Collection c){ + System.out.println(pformat(c)); + } + + public static void pprint(Object[] c){ + System.out.println(pformat(Arrays.asList(c))); + } +} diff --git a/src/btp/oneP/PostOffice.java b/src/btp/oneP/PostOffice.java new file mode 100644 index 0000000..76b89c5 --- /dev/null +++ b/src/btp/oneP/PostOffice.java @@ -0,0 +1,152 @@ +package btp.oneP; + +import java.util.Iterator; + +public class PostOffice { + enum MailHandler{ + GENERAL_DELIVERY{ + + @Override + boolean handle(Mail m) { + switch(m.generalDelivery){ + case YES: + System.out.print("Using general delivery for " + m);return true; + default:return false; + } + } + + }, + MACHINE_SAN{ + + @Override + boolean handle(Mail m) { + switch(m.scannability){ + case UNSCANNABLE:return false; + default: + switch(m.address){ + case INCORRECT:return false; + default: + System.out.print("Delivering " + m +" automatically"); + return true; + } + } + } + + }, + VISUAL_INSPECTION{ + + @Override + boolean handle(Mail m) { + switch(m.readability){ + case ILLEGIBLE:return false; + default: + switch(m.address){ + case INCORRECT:return false; + default: + System.out.print("Delivering " + m + " normally"); + return true; + } + } + } + + }, + RETURN_TO_SENDER{ + + @Override + boolean handle(Mail m) { + switch(m.returnAddress){ + case MISSING:return false; + default: + System.out.print("Returning " + m + " to sender"); + return true; + } + } + + }; + abstract boolean handle(Mail m); + } + static void handle(Mail m){ + for(MailHandler handler : MailHandler.values()){ + if(handler.handle(m)){ + return; + } + } + System.out.println(m + " is a dead letter"); + } + public static void main(String[] args) { + for(Mail mail : Mail.generator(10)){ + System.out.print(mail.details()); + handle(mail); + System.out.println("***"); + } + } + +} + +class Mail{ + enum GeneralDelivery{ + YES,NO1,NO2,NO3,NO4,NO5 + } + enum Scannability{ + UNSCANNABLE,YES1,YES2,YES3,YES4 + } + enum Readability{ + ILLEGIBLE,YES1,YES2,YES3,YES4 + } + enum Address{ + INCORRECT,OK1,OK2,OK3,OK4,OK5,OK6 + } + enum ReturnAddress{ + MISSING,OK1,OK2,OK3,OK4,OK5 + } + GeneralDelivery generalDelivery; + Scannability scannability; + Readability readability; + Address address; + ReturnAddress returnAddress; + static long counter = 0; + long id = counter++; + public String toString(){ + return "Mail " + id; + } + public String details(){ + return toString()+ + ", General Delivery: " + generalDelivery + + ", Address Scannability: " + scannability + + ", Address readability: "+ readability + + ", Address Address: " + address + + ", Return address: " + returnAddress; + } + + public static Mail randomMail(){ + Mail m = new Mail(); + m.generalDelivery = Enums.random(GeneralDelivery.class); + m.scannability = Enums.random(Scannability.class); + m.readability = Enums.random(Readability.class); + m.address = Enums.random(Address.class); + m.returnAddress = Enums.random(ReturnAddress.class); + return m; + } + public static Iterable generator(final int count){ + return new Iterable(){ + int n = count; + @Override + public Iterator iterator() { + return new Iterator(){ + + @Override + public boolean hasNext() { + return n-- > 0; + } + + @Override + public Mail next() { + return randomMail(); + } + + }; + } + + }; + } +} diff --git a/src/btp/oneP/PreferencesDemo.java b/src/btp/oneP/PreferencesDemo.java new file mode 100644 index 0000000..dd85e8c --- /dev/null +++ b/src/btp/oneP/PreferencesDemo.java @@ -0,0 +1,23 @@ +package btp.oneP; + +import java.util.prefs.BackingStoreException; +import java.util.prefs.Preferences; + +public class PreferencesDemo { + + public static void main(String[] args) throws BackingStoreException { + Preferences prefs = Preferences.userNodeForPackage(PreferencesDemo.class); + prefs.put("Location", "Oz"); + prefs.put("Footwear", "Ruby Slippers"); + prefs.putInt("Companions", 4); + prefs.putBoolean("Are there witched?", true); + int usageCount = prefs.getInt("UsageCount", 0); + usageCount++; + prefs.putInt("UsageCount", usageCount); + for(String key : prefs.keys()){ + System.out.println(key+":"+prefs.get(key, null)); + } + System.out.println("How many companions does Derothy have?"+prefs.getInt("Companions", 0)); + } + +} diff --git a/src/btp/oneP/PriorityQueueTst.java b/src/btp/oneP/PriorityQueueTst.java new file mode 100644 index 0000000..62f7087 --- /dev/null +++ b/src/btp/oneP/PriorityQueueTst.java @@ -0,0 +1,38 @@ +package btp.oneP; + +import java.util.PriorityQueue; +import java.util.Random; + +public class PriorityQueueTst { + + public static void main(String[] args) { + PriorityQueue pq = new PriorityQueue(); + for(int i=0;i<10;i++){ + pq.add(new IntegerPriority()); + } + System.out.println(pq); + while(!pq.isEmpty()){ + System.out.println(pq.poll()); + System.out.println(pq); + } + } + + static class IntegerPriority implements Comparable{ + Integer i; + private Random rd = new Random(); + public IntegerPriority(){ + i = rd.nextInt(100); + } + @Override + public int compareTo(IntegerPriority o) { + if(this.i>o.i){ + return -1; + }else if(this.i < o.i){ + return 1; + }else return 0; + } + public String toString(){ + return Integer.toString(i); + } + } +} diff --git a/src/btp/oneP/ProcessFiles.java b/src/btp/oneP/ProcessFiles.java new file mode 100644 index 0000000..cd75b5d --- /dev/null +++ b/src/btp/oneP/ProcessFiles.java @@ -0,0 +1,56 @@ +package btp.oneP; + +import java.io.File; +import java.io.IOException; + +public class ProcessFiles { + public interface Strategy{ + void process(File file); + } + + private Strategy strategy; + private String ext; + + public ProcessFiles(Strategy strategy,String ext){ + this.strategy = strategy; + this.ext = ext; + } + + public void start(String...args){ + try{ + if(args.length == 0){ + processDirectoryTree(new File(System.getProperty("user.dir"))); + }else{ + for(String arg : args){ + File fileArg = new File(arg); + if(fileArg.isDirectory()){ + processDirectoryTree(fileArg); + }else{ + if(!arg.endsWith("."+ext)){ + arg += "." + ext; + } + strategy.process(new File(arg).getCanonicalFile()); + + } + } + } + }catch(IOException e){ + throw new RuntimeException(); + } + } + + public void processDirectoryTree(File root) throws IOException{ + for(File file : Directory.walk(root.getAbsolutePath(), ".*\\."+ext)){ + strategy.process(file.getCanonicalFile()); + } + } + public static void main(String[] args) { + new ProcessFiles(new Strategy() { + @Override + public void process(File file) { + System.out.println(file); + } + },"java").start("E:\\workspaces\\NewWork\\Study\\src\\btp\\oneP");; + } + +} diff --git a/src/btp/oneP/ProcessTest.java b/src/btp/oneP/ProcessTest.java new file mode 100644 index 0000000..82bb9ec --- /dev/null +++ b/src/btp/oneP/ProcessTest.java @@ -0,0 +1,24 @@ +package btp.oneP; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class ProcessTest { + + public static void main(String[] args) { + try{ + //Process proc = Runtime.getRuntime().exec("ipconfig"); + Process proc = new ProcessBuilder("winver").start(); + BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); + String s; + while((s = br.readLine()) != null){ + System.out.println(s); + } + System.out.println(System.getProperty("java.io.tmpdirs")); + }catch(IOException e){ + e.printStackTrace(); + } + } + +} diff --git a/src/btp/oneP/QueueBehavior.java b/src/btp/oneP/QueueBehavior.java new file mode 100644 index 0000000..c9d8b22 --- /dev/null +++ b/src/btp/oneP/QueueBehavior.java @@ -0,0 +1,41 @@ +package btp.oneP; + +import java.util.LinkedList; +import java.util.PriorityQueue; +import java.util.Queue; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.PriorityBlockingQueue; + +public class QueueBehavior { + private static int count = 10; + static void test(Queue queue,GeneratorN gen){ + for(int i=0;i{ + String[] s = ("one two three four five six seven eight nine ten").split(" "); + int i; + @Override + public String next() { + return s[i++]; + } + + } + + public static void main(String[] args) { + test(new LinkedList(),new Gen()); + test(new PriorityQueue(),new Gen()); + test(new ArrayBlockingQueue(count),new Gen()); + test(new ConcurrentLinkedQueue(),new Gen()); + test(new LinkedBlockingQueue(),new Gen()); + test(new PriorityBlockingQueue(),new Gen()); + } + +} diff --git a/src/btp/oneP/RandomTest.java b/src/btp/oneP/RandomTest.java new file mode 100644 index 0000000..6a4d234 --- /dev/null +++ b/src/btp/oneP/RandomTest.java @@ -0,0 +1,15 @@ +package btp.oneP; + +public class RandomTest { + + public static void main(String[] args) { + for(int i = 0; i < 20 ; i++){ + System.out.print(Enums.random(Activity.class) + " "); + } + } + +} + +enum Activity{ + SITTING,LYING,STANING,HOPPONG,RUNNING,DOGGING,JUMPING,FALLING,FLYING +} diff --git a/src/btp/oneP/ReadOnly.java b/src/btp/oneP/ReadOnly.java new file mode 100644 index 0000000..2cce919 --- /dev/null +++ b/src/btp/oneP/ReadOnly.java @@ -0,0 +1,40 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; + +public class ReadOnly { + static Collection data = new ArrayList(Countries.names(5)); + public static void main(String[] args) { + Collection c = Collections.unmodifiableCollection(new ArrayList(data)); + System.out.println(c); + //c.add("one");//error + + List a = Collections.unmodifiableList(new ArrayList(data)); + ListIterator lit = a.listIterator(); + System.out.println(lit.next()); + //lit.add("one");//error + + Set s = Collections.unmodifiableSet(new HashSet(data)); + System.out.println(s); + //s.add("one");//error + + Set ss = Collections.unmodifiableSortedSet(new TreeSet(data)); + + Map m = Collections.unmodifiableMap(new HashMap(Countries.capitals(6))); + System.out.println(m); + + Map sm = Collections.unmodifiableSortedMap(new TreeMap(Countries.capitals(6))); + System.out.println(sm); + } + +} diff --git a/src/btp/oneP/Redirecting.java b/src/btp/oneP/Redirecting.java new file mode 100644 index 0000000..a7f29bd --- /dev/null +++ b/src/btp/oneP/Redirecting.java @@ -0,0 +1,31 @@ +package btp.oneP; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; + +public class Redirecting { + + public static void main(String[] args) throws IOException { + PrintStream console = System.out; + BufferedInputStream in = new BufferedInputStream(new FileInputStream("E:\\workspaces\\NewWork\\Study\\src\\btp\\oneP\\Redirecting.java")); + PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\test.out"))); + System.setIn(in); + System.setOut(out); + System.setErr(out); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String s; + while((s = br.readLine()) != null){ + System.out.println(s); + } + out.close(); + System.setOut(console); + } + +} diff --git a/src/btp/oneP/References.java b/src/btp/oneP/References.java new file mode 100644 index 0000000..976c875 --- /dev/null +++ b/src/btp/oneP/References.java @@ -0,0 +1,57 @@ +package btp.oneP; + +import java.lang.ref.PhantomReference; +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.SoftReference; +import java.lang.ref.WeakReference; +import java.util.LinkedList; + +public class References { + + private static ReferenceQueue rq = + new ReferenceQueue(); + public static void checkQueue(){ + Reference inq = rq.poll(); + if(null != inq){ + System.out.println("In queue: "+inq.get()); + } + } + + public static void main(String[] args) { + int size = 10; + if(args.length > 0){ + size = new Integer(args[0]); + } + + LinkedList> sa = new LinkedList>(); + + for(int i=0;i(new VeryBig("Soft "+i),rq)); + System.out.println("Just created: "+sa.getLast()); + checkQueue(); + } + System.out.println("--------------------"); + + LinkedList> wa = new LinkedList>(); + + for(int i=0;i(new VeryBig("Weak "+i),rq)); + System.out.println("Just created: "+wa.getLast()); + checkQueue(); + } + System.out.println("--------------------"); + + SoftReference s = new SoftReference(new VeryBig("Soft")); + WeakReference w = new WeakReference(new VeryBig("Weak")); + System.gc(); + LinkedList> pa = + new LinkedList>(); + for(int i=0;i(new VeryBig("Phantom "+i),rq)); + System.out.println("Just created: "+pa.getLast()); + checkQueue(); + } + } + +} diff --git a/src/btp/oneP/Reflection.java b/src/btp/oneP/Reflection.java new file mode 100644 index 0000000..882a2ba --- /dev/null +++ b/src/btp/oneP/Reflection.java @@ -0,0 +1,35 @@ +package btp.oneP; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.Set; +import java.util.TreeSet; + +public class Reflection { + public static Set analyze(Class enumClass){ + System.out.println("----- Analyze " + enumClass + " -----"); + System.out.println("Interfaces:"); + for(Type t : enumClass.getGenericInterfaces()){ + System.out.print(t+" "); + } + System.out.println("Base: "+enumClass.getSuperclass()); + Set methods = new TreeSet(); + for(Method m : enumClass.getMethods()){ + methods.add(m.getName()); + } + return methods; + } + + public static void main(String[] args) { + Set exploreMethods = analyze(Explore.class); + Set enumMethods = analyze(Enum.class); + System.out.println("Explore.containsAll(Enum)?"+exploreMethods.containsAll(enumMethods)); + System.out.println("Explore.removeAll(Enum):"); + exploreMethods.removeAll(enumMethods); + System.out.println(enumMethods); + System.out.println(exploreMethods); + } + +} + +enum Explore{HERE,THERE} diff --git a/src/btp/oneP/RoShamBo1.java b/src/btp/oneP/RoShamBo1.java new file mode 100644 index 0000000..20a9673 --- /dev/null +++ b/src/btp/oneP/RoShamBo1.java @@ -0,0 +1,125 @@ +package btp.oneP; + +import java.util.Random; + +public class RoShamBo1 { + static final int SIZE = 20; + private static Random rand = new Random(47); + public static Item newItem(){ + switch(rand.nextInt(3)){ + default: + case 0:return new Scissors(); + case 1:return new Paper(); + case 2:return new Rock(); + } + } + public static void match(Item a,Item b){ + System.out.println(a + " vs "+ b +": " + a.compete(b)); + } + public static void main(String[] args) { + // TODO Auto-generated method stub + for(int i = 0;i < SIZE;i++){ + match(newItem(),newItem()); + } + } + +} + +enum Outcome{ + WIN,LOSE,DRAW +} + +interface Item{ + Outcome compete(Item it); + Outcome eval(Paper p); + Outcome eval(Scissors s); + Outcome eval(Rock r); +} + +class Paper implements Item{ + + @Override + public Outcome compete(Item it) { + return it.eval(this); + } + + @Override + public Outcome eval(Paper p) { + // TODO Auto-generated method stub + return Outcome.DRAW; + } + + @Override + public Outcome eval(Scissors s) { + // TODO Auto-generated method stub + return Outcome.WIN; + } + + @Override + public Outcome eval(Rock r) { + // TODO Auto-generated method stub + return Outcome.LOSE; + } + public String toString(){ + return "Paper"; + } + +} +class Scissors implements Item{ + + @Override + public Outcome compete(Item it) { + return it.eval(this); + } + + @Override + public Outcome eval(Paper p) { + // TODO Auto-generated method stub + return Outcome.LOSE; + } + + @Override + public Outcome eval(Scissors s) { + // TODO Auto-generated method stub + return Outcome.DRAW; + } + + @Override + public Outcome eval(Rock r) { + // TODO Auto-generated method stub + return Outcome.WIN; + } + public String toString(){ + return "Scissors"; + } + +} +class Rock implements Item{ + + @Override + public Outcome compete(Item it) { + return it.eval(this); + } + + @Override + public Outcome eval(Paper p) { + // TODO Auto-generated method stub + return Outcome.WIN; + } + + @Override + public Outcome eval(Scissors s) { + // TODO Auto-generated method stub + return Outcome.LOSE; + } + + @Override + public Outcome eval(Rock r) { + // TODO Auto-generated method stub + return Outcome.DRAW; + } + public String toString(){ + return "Rock"; + } + +} diff --git a/src/btp/oneP/RoShamBo2.java b/src/btp/oneP/RoShamBo2.java new file mode 100644 index 0000000..4aeab49 --- /dev/null +++ b/src/btp/oneP/RoShamBo2.java @@ -0,0 +1,40 @@ +package btp.oneP; +import static btp.oneP.Outcome.*; +public enum RoShamBo2 implements Competitor{ + PAPER(DRAW,LOSE,WIN), + SCISSORS(WIN,DRAW,LOSE), + ROCK(LOSE,WIN,DRAW); + private Outcome vPAPER,vSCISSORS,vROCK; + RoShamBo2(Outcome paper,Outcome scissors,Outcome rock){ + this.vPAPER = paper; + this.vSCISSORS = scissors; + this.vROCK = rock; + } + public Outcome compete(RoShamBo2 it){ + switch(it){ + default: + case PAPER:return vPAPER; + case SCISSORS:return vSCISSORS; + case ROCK:return vROCK; + } + } + public static void main(String[] args) { + RoShamBo.play(RoShamBo2.class, 20); + } + +} + +interface Competitor>{ + Outcome compete(T compepitor); +} + +class RoShamBo{ + public static > void match(T a,T b){ + System.out.println(a + " vs " + b + ": " + a.compete(b)); + } + public static & Competitor> void play(Class rsbClass,int size){ + for(int i = 0; i{ + PAPER{ + public Outcome compete(RoShamBo3 it){ + switch(it){ + default: + case PAPER:return DRAW; + case SCISSORS:return LOSE; + case ROCK:return WIN; + } + } + }, + SCISSORS{ + public Outcome compete(RoShamBo3 it){ + switch(it){ + default: + case PAPER:return WIN; + case SCISSORS:return DRAW; + case ROCK:return LOSE; + } + } + }, + ROCK{ + public Outcome compete(RoShamBo3 it){ + switch(it){ + default: + case PAPER:return LOSE; + case SCISSORS:return WIN; + case ROCK:return DRAW; + } + } + }; + public static void main(String[] args) { + RoShamBo.play(RoShamBo2.class, 20); + } + + + +} diff --git a/src/btp/oneP/RoShamBo4.java b/src/btp/oneP/RoShamBo4.java new file mode 100644 index 0000000..8a858f7 --- /dev/null +++ b/src/btp/oneP/RoShamBo4.java @@ -0,0 +1,32 @@ +package btp.oneP; + +public enum RoShamBo4 implements Competitor{ + ROCK{ + @Override + public Outcome compete(RoShamBo4 opponent) { + // TODO Auto-generated method stub + return compete(SCISSORS,opponent); + } + }, + SCISSORS{ + @Override + public Outcome compete(RoShamBo4 opponent) { + // TODO Auto-generated method stub + return compete(PAPER,opponent); + } + }, + PAPER{ + @Override + public Outcome compete(RoShamBo4 opponent) { + // TODO Auto-generated method stub + return compete(ROCK,opponent); + } + }; + + Outcome compete(RoShamBo4 loser,RoShamBo4 opponent){ + return ((opponent == this)? Outcome.DRAW:((opponent == loser) ? Outcome.WIN : Outcome.LOSE)); + } + public static void main(String...args){ + RoShamBo.play(RoShamBo4.class, 20); + } +} diff --git a/src/btp/oneP/RoShamBo5.java b/src/btp/oneP/RoShamBo5.java new file mode 100644 index 0000000..128d1ae --- /dev/null +++ b/src/btp/oneP/RoShamBo5.java @@ -0,0 +1,35 @@ +package btp.oneP; +import java.util.EnumMap; +import static btp.oneP.Outcome.*; + +public enum RoShamBo5 implements Competitor{ + PAPER,SCISSORS,ROCK; + + static EnumMap> table = + new EnumMap>(RoShamBo5.class); + + static{ + for(RoShamBo5 it : values()){ + table.put(it, new EnumMap(RoShamBo5.class)); + } + initRow(PAPER,DRAW,LOSE,WIN); + initRow(SCISSORS,WIN,DRAW,LOSE); + initRow(ROCK,LOSE,WIN,DRAW); + } + + static void initRow(RoShamBo5 it,Outcome vPaper,Outcome vScissors,Outcome vRock){ + EnumMap row = table.get(it); + row.put(RoShamBo5.PAPER, vPaper); + row.put(RoShamBo5.SCISSORS, vScissors); + row.put(RoShamBo5.ROCK, vRock); + } + + @Override + public Outcome compete(RoShamBo5 compepitor) { + return table.get(this).get(compepitor); + } + + public static void main(String...args){ + RoShamBo.play(RoShamBo5.class, 20); + } +} diff --git a/src/btp/oneP/RoShamBo6.java b/src/btp/oneP/RoShamBo6.java new file mode 100644 index 0000000..315c1ff --- /dev/null +++ b/src/btp/oneP/RoShamBo6.java @@ -0,0 +1,18 @@ +package btp.oneP; +import static btp.oneP.Outcome.*; +public enum RoShamBo6 implements Competitor{ + PAPER,SCISSORS,ROCK; + private static Outcome[][] table = { + {DRAW,LOSE,WIN}, + {WIN,DRAW,LOSE}, + {LOSE,WIN,DRAW} + }; + @Override + public Outcome compete(RoShamBo6 compepitor) { + // TODO Auto-generated method stub + return table[this.ordinal()][compepitor.ordinal()]; + } + public static void main(String...args){ + RoShamBo.play(RoShamBo6.class, 20); + } +} diff --git a/src/btp/oneP/SameFather.java b/src/btp/oneP/SameFather.java new file mode 100644 index 0000000..7cef77e --- /dev/null +++ b/src/btp/oneP/SameFather.java @@ -0,0 +1,38 @@ +package btp.oneP; + +public class SameFather { + + public static void main(String[] args) { + Child1 c1 = new Child1(); + new Child2(); + } + +} + + +class Father{ + { + System.out.println("Father now!"); + } + public Father(){ + System.out.println("Father"); + } +} + +class Child1 extends Father{ + { + System.out.println("Child1 now!"); + } + public Child1(){ + System.out.println("Child1"); + } +} + +class Child2 extends Father{ + { + System.out.println("Child2 now!"); + } + public Child2(){ + System.out.println("Child2"); + } +} diff --git a/src/btp/oneP/SecurityCategory.java b/src/btp/oneP/SecurityCategory.java new file mode 100644 index 0000000..abc46cf --- /dev/null +++ b/src/btp/oneP/SecurityCategory.java @@ -0,0 +1,22 @@ +package btp.oneP; + +public enum SecurityCategory { + STOCK(Security.Stock.class),BOND(Security.Bond.class); + Security[] values; + SecurityCategory(Class kind){ + values = kind.getEnumConstants(); + } + interface Security{ + enum Stock implements Security{SHORT,LONG,MARGIN} + enum Bond implements Security{MUNICIPAL,JUNK} + } + public Security randomSelection(){ + return Enums.random(values); + } + public static void main(String[] args){ + for(int i=0;i<10;i++){ + SecurityCategory category = Enums.random(SecurityCategory.class); + System.out.println(category + ": " + category.randomSelection()); + } + } +} diff --git a/src/btp/oneP/SerialCtl.java b/src/btp/oneP/SerialCtl.java new file mode 100644 index 0000000..f32b12c --- /dev/null +++ b/src/btp/oneP/SerialCtl.java @@ -0,0 +1,46 @@ +package btp.oneP; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; + +public class SerialCtl implements Serializable { + private String a; + private transient String b; + { + System.out.println("实例初始化"); + } + public SerialCtl(){ + System.out.println("SerialCtl()"); + } + public SerialCtl(String aa,String bb){ + System.out.println("SerialCtl(String,String)"); + a = "Not Transient:"+aa; + b = "Transient:"+bb; + } + public String toString(){ + return a + "\n" + b; + } + private void writeObject(ObjectOutputStream stream) throws IOException{ + stream.defaultWriteObject(); + stream.writeObject(b); + } + private void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException{ + stream.defaultReadObject(); + b = (String) stream.readObject(); + } + public static void main(String[] args) throws IOException, ClassNotFoundException { + SerialCtl sc = new SerialCtl("Test1","Test2"); + System.out.println("Before:\n"+sc); + ByteArrayOutputStream buf = new ByteArrayOutputStream(); + ObjectOutputStream o = new ObjectOutputStream(buf); + o.writeObject(sc); + ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buf.toByteArray())); + SerialCtl sc2 = (SerialCtl) in.readObject(); + System.out.println("After:\n"+sc2); + } + +} diff --git a/src/btp/oneP/SimpleHashMap.java b/src/btp/oneP/SimpleHashMap.java new file mode 100644 index 0000000..61eb305 --- /dev/null +++ b/src/btp/oneP/SimpleHashMap.java @@ -0,0 +1,72 @@ +package btp.oneP; + +import java.util.AbstractMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.ListIterator; +import java.util.Map; +import java.util.Set; + +public class SimpleHashMap extends AbstractMap{ + + static final int size = 997; + @SuppressWarnings("unchecked") + LinkedList>[] buckets = new LinkedList[size]; + + public V put(K key,V value){ + V oldValue = null; + int index = Math.abs(key.hashCode())%size; + if(buckets[index] == null){ + buckets[index] = new LinkedList>(); + } + LinkedList> bucket = buckets[index]; + MapEntry pair = new MapEntry(key,value); + boolean found = false; + ListIterator> it = bucket.listIterator(); + while(it.hasNext()){ + MapEntry ipair = it.next(); + if(ipair.getKey().equals(key)){ + oldValue = ipair.getValue(); + it.set(pair); + found = true; + break; + } + } + if(!found){ + buckets[index].add(pair); + } + return oldValue; + } + + public V get(Object key){ + int index = Math.abs(key.hashCode())%size; + if(buckets[index] == null)return null; + for(MapEntry ipair:buckets[index]){ + if(ipair.getKey().equals(key)){ + return ipair.getValue(); + } + } + return null; + } + + + @Override + public Set> entrySet() { + Set> set = new HashSet>(); + for(LinkedList> bucket:buckets){ + if(bucket == null) continue; + for(MapEntry mpair:bucket){ + set.add(mpair); + } + } + return set; + } + + public static void main(String[] args) { + SimpleHashMap m = new SimpleHashMap(); + m.putAll(Countries.capitals(25)); + System.out.println(m); + System.out.println(m.get("CHINA")); + System.out.println(m.entrySet()); + } +} diff --git a/src/btp/oneP/SlowMap.java b/src/btp/oneP/SlowMap.java new file mode 100644 index 0000000..6b53a71 --- /dev/null +++ b/src/btp/oneP/SlowMap.java @@ -0,0 +1,78 @@ +package btp.oneP; + +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class SlowMap extends AbstractMap{ + private List keys = new ArrayList(); + private List values = new ArrayList(); + public V put(K key,V value){ + V oldValue = get(key); + if(!keys.contains(key)){ + keys.add(key); + values.add(value); + }else{ + values.set(keys.indexOf(key), value); + } + return oldValue; + } + + public V get(Object key){ + if(!keys.contains(key)){ + return null; + }else{ + return values.get(keys.indexOf(key)); + } + } + + @Override + public Set> entrySet() { + // TODO Auto-generated method stub + Set> set = new HashSet>(); + Iterator ki = keys.iterator(); + Iterator vi = values.iterator(); + while(ki.hasNext()){ + set.add(new Map.Entry() { + K k = ki.next(); + V v = vi.next(); + @Override + public K getKey() { + // TODO Auto-generated method stub + return k; + } + + @Override + public V getValue() { + // TODO Auto-generated method stub + return v; + } + + @Override + public V setValue(V value) { + v = value; + return v; + } + + public String toString(){ + return k+"="+v; + } + }); + } + return set; + } + + public static void main(String...args){ + SlowMap m = new SlowMap(); + m.putAll(Countries.capitals()); + System.out.println(m); + System.out.println(m.get("Japan")); + //不按插入顺序打印,set + System.out.println(m.entrySet()); + } + +} diff --git a/src/btp/oneP/SortedMapDemo.java b/src/btp/oneP/SortedMapDemo.java new file mode 100644 index 0000000..3cb4532 --- /dev/null +++ b/src/btp/oneP/SortedMapDemo.java @@ -0,0 +1,33 @@ +package btp.oneP; + +import java.util.Iterator; +import java.util.SortedMap; +import java.util.TreeMap; + +public class SortedMapDemo { + + public static void main(String[] args) { + SortedMap sortedMap = new TreeMap(new CountingMapData(10)); + System.out.println(sortedMap); + Integer low = sortedMap.firstKey(); + Integer high = sortedMap.lastKey(); + System.out.println(low); + System.out.println(high); + Iterator it = sortedMap.keySet().iterator(); + for(int i=0;i<=6;i++){ + if(i == 3){ + low = it.next(); + } + if(i == 6){ + high = it.next(); + } + else it.next(); + } + System.out.println(low); + System.out.println(high); + System.out.println(sortedMap.subMap(low, high)); + System.out.println(sortedMap.headMap(high)); + System.out.println(sortedMap.tailMap(low)); + } + +} diff --git a/src/btp/oneP/SortedSetDemo.java b/src/btp/oneP/SortedSetDemo.java new file mode 100644 index 0000000..9691b15 --- /dev/null +++ b/src/btp/oneP/SortedSetDemo.java @@ -0,0 +1,35 @@ +package btp.oneP; + +import java.util.Collections; +import java.util.Iterator; +import java.util.SortedSet; +import java.util.TreeSet; + +public class SortedSetDemo { + + public static void main(String[] args) { + SortedSet sortedSet = new TreeSet(); + Collections.addAll(sortedSet, "one two three four five six seven eight".split(" ")); + System.out.println(sortedSet); + + String low = sortedSet.first(); + String high = sortedSet.last(); + System.out.println(low); + System.out.println(high); + + Iterator it = sortedSet.iterator(); + for(int i = 0;i<=6;i++){ + if(i == 3) low = it.next(); + if(i == 6)high = it.next(); + else it.next(); + } + + System.out.println(low); + System.out.println(high); + + System.out.println(sortedSet.subSet(low, high)); + System.out.println(sortedSet.headSet(high)); + System.out.println(sortedSet.tailSet(low)); + } + +} diff --git a/src/btp/oneP/SpaceShip.java b/src/btp/oneP/SpaceShip.java new file mode 100644 index 0000000..637b31b --- /dev/null +++ b/src/btp/oneP/SpaceShip.java @@ -0,0 +1,15 @@ +package btp.oneP; + +public enum SpaceShip { + SCOUT,CARGO,TRANSPORT,CRUISER,BATTLESHIP,MOTHERSHIP; + public String toString(){ + String id = name(); + String lower = id.substring(1).toLowerCase(); + return id.charAt(0) + lower; + } + public static void main(String...args){ + for(SpaceShip s : values()){ + System.out.println(s); + } + } +} diff --git a/src/btp/oneP/SpringDetector.java b/src/btp/oneP/SpringDetector.java new file mode 100644 index 0000000..adf10a0 --- /dev/null +++ b/src/btp/oneP/SpringDetector.java @@ -0,0 +1,68 @@ +package btp.oneP; + +import java.lang.reflect.Constructor; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +public class SpringDetector { + + public static void detectSpring(Class type) throws Exception{ + Constructor ghog = type.getConstructor(Integer.TYPE); + Map map = new HashMap(); + for(int i = 0;i<10;i++){ + map.put(ghog.newInstance(i), new Prediction()); + } + System.out.println("map = "+map); + Groundhog gh = ghog.newInstance(3); + System.out.println("Looking up prediction for "+gh); + if(map.containsKey(gh)){ + System.out.println(map.get(gh)); + }else{ + System.out.println("key not found:"+gh); + } + } + + public static void main(String[] args) throws Exception{ + //detectSpring(Groundhog.class); + SpringDetector.detectSpring(Groundhog2.class); + } + +} + +class Groundhog{ + protected int number; + public Groundhog(int n){ + number = n; + } + public String toString(){ + return "Groundhog #"+number; + } +} + +class Prediction{ + private static Random rand = new Random(47); + private boolean shadow = rand.nextDouble()>0.5; + public String toString(){ + if(shadow){ + return "Six more weeks of winter!"; + }else{ + return "Early Spring!"; + } + } +} + +class Groundhog2 extends Groundhog{ + + public Groundhog2(int n) { + super(n); + } + public int hashCode(){ + return number; + } + public boolean equals(Object o){ + //return o instanceof Groundhog2 && (number == ((Groundhog2)o).number); + return o instanceof Groundhog2 && (this.hashCode() == ((Groundhog2)o).hashCode()); + } + +} diff --git a/src/btp/oneP/Stacks.java b/src/btp/oneP/Stacks.java new file mode 100644 index 0000000..5ded04a --- /dev/null +++ b/src/btp/oneP/Stacks.java @@ -0,0 +1,30 @@ +package btp.oneP; +import java.util.*; +public class Stacks { + + public static void main(String[] args) { + java.util.Stack stack = new java.util.Stack(); + for(Month m:Month.values()){ + stack.push(m.toString()); + } + stack.addElement("The last line"); + System.out.println("element 5 = "+stack.elementAt(5)); + System.out.println("popping elements:"); + while(!stack.empty()){ + System.out.println(stack.pop()+" "); + } + LinkedList lstack = new LinkedList(); + for(Month m : Month.values()){ + lstack.addFirst(m.toString()); + } + System.out.println("lstack = "+lstack); + while(!lstack.isEmpty()){ + System.out.println(lstack.removeFirst() + " "); + } + } + +} + +enum Month{ + JANUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER +} diff --git a/src/btp/oneP/StoreCADState.java b/src/btp/oneP/StoreCADState.java new file mode 100644 index 0000000..5bea6d2 --- /dev/null +++ b/src/btp/oneP/StoreCADState.java @@ -0,0 +1,115 @@ +package btp.oneP; + +import java.io.ByteArrayOutputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class StoreCADState { + + public static void main(String[] args) throws IOException { + List> shapeTypes = new ArrayList>(); + shapeTypes.add(CircleX.class); + shapeTypes.add(SquareX.class); + shapeTypes.add(LineX.class); + + List shapes = new ArrayList(); + for(int i = 0;i < 10; i++){ + shapes.add(ShapeX.randomFactory()); + } + for(int i = 0;i < 10; i++){ + ((ShapeX)shapes.get(i)).setColor(ShapeX.GREEN); + } + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream out = new ObjectOutputStream(bout); + out.writeObject(shapeTypes); + LineX.serializeStaticState(out); + out.writeObject(shapes); + System.out.println(shapes); + } + +} + +abstract class ShapeX implements Serializable{ + public static final int RED = 1,BLUE = 2,GREEN = 3; + private int xPos,yPos,dimension; + private static Random rand = new Random(); + private static int counter = 0; + public abstract void setColor(int newColor); + public abstract int getColor(); + public ShapeX(int xVal,int yVal,int dim){ + this.xPos = xVal; + this.yPos = yVal; + this.dimension = dim; + } + public String toString(){ + return this.getClass()+ + "color["+getColor()+"] xPos["+xPos+ + "] yPos["+yPos+"] dim["+dimension+"]\n"; + } + public static ShapeX randomFactory(){ + int xVal = rand.nextInt(100); + int yVal = rand.nextInt(100); + int dim = rand.nextInt(100); + switch(counter++ % 3){ + default: + case 0:return new CircleX(xVal,yVal,dim); + case 1:return new SquareX(xVal,yVal,dim); + case 2:return new LineX(xVal,yVal,dim); + } + } +} + +class CircleX extends ShapeX{ + private static int color = RED; + public CircleX(int xVal, int yVal, int dim) { + super(xVal, yVal, dim); + // TODO Auto-generated constructor stub + } + public void setColor(int newColor){ + color = newColor; + } + public int getColor(){ + return color; + } +} + +class SquareX extends ShapeX{ + private static int color; + public SquareX(int xVal, int yVal, int dim) { + super(xVal, yVal, dim); + color = RED; + } + public void setColor(int newColor){ + color = newColor; + } + public int getColor(){ + return color; + } +} + +class LineX extends ShapeX{ + private static int color = RED; + public static void serializeStaticState(ObjectOutputStream os) throws IOException{ + os.writeInt(color);; + } + public static void deserializeStaticState(ObjectInputStream os) throws IOException{ + color = os.readInt(); + } + public LineX(int xVal, int yVal, int dim) { + super(xVal, yVal, dim); + // TODO Auto-generated constructor stub + } + public void setColor(int newColor){ + color = newColor; + } + public int getColor(){ + return color; + } + +} diff --git a/src/btp/oneP/StoringAndRecoveringData.java b/src/btp/oneP/StoringAndRecoveringData.java new file mode 100644 index 0000000..ced6fc3 --- /dev/null +++ b/src/btp/oneP/StoringAndRecoveringData.java @@ -0,0 +1,29 @@ +package btp.oneP; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; + +public class StoringAndRecoveringData { + + public static void main(String[] args) throws IOException { + DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\Data.txt"))); + out.writeDouble(3.14159); + out.writeUTF("That is pi"); + out.writeDouble(1.41413); + out.writeUTF("Square root of 2"); + out.close(); + DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("C:\\Users\\dell\\Desktop\\IO\\Data.txt"))); + + //读的顺序必须和写的顺序一致 + System.out.println(in.readDouble()); + System.out.println(in.readUTF()); + System.out.println(in.readDouble()); + System.out.println(in.readUTF()); + } + +} diff --git a/src/btp/oneP/Synchronization.java b/src/btp/oneP/Synchronization.java new file mode 100644 index 0000000..50945e9 --- /dev/null +++ b/src/btp/oneP/Synchronization.java @@ -0,0 +1,22 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; + +public class Synchronization { + public static void main(String...args){ + Collections.synchronizedCollection(new ArrayList()); + List list = Collections.synchronizedList(new ArrayList()); + Set s = Collections.synchronizedSet(new HashSet()); + Set ss = Collections.synchronizedSortedSet(new TreeSet()); + Map m = Collections.synchronizedMap(new HashMap()); + Map sm = Collections.synchronizedSortedMap(new TreeMap()); + } +} diff --git a/src/btp/oneP/TestCollection.java b/src/btp/oneP/TestCollection.java new file mode 100644 index 0000000..2cbd09e --- /dev/null +++ b/src/btp/oneP/TestCollection.java @@ -0,0 +1,9 @@ +package btp.oneP; + +public abstract class TestCollection { + String name; + public TestCollection(String name){ + this.name = name; + } + abstract int test(C container,TestParam tp); +} diff --git a/src/btp/oneP/TestEOF.java b/src/btp/oneP/TestEOF.java new file mode 100644 index 0000000..22206b1 --- /dev/null +++ b/src/btp/oneP/TestEOF.java @@ -0,0 +1,18 @@ +package btp.oneP; + +import java.io.BufferedInputStream; +import java.io.DataInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; + +public class TestEOF { + + public static void main(String[] args) throws IOException { + DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("E:\\workspaces\\NewWork\\Study\\src\\btp\\oneP\\TestEOF.java"))); + while(in.available() != 0){ + System.out.print((char)in.readByte()); + } + } + +} diff --git a/src/btp/oneP/TestParam.java b/src/btp/oneP/TestParam.java new file mode 100644 index 0000000..37989fb --- /dev/null +++ b/src/btp/oneP/TestParam.java @@ -0,0 +1,26 @@ +package btp.oneP; + +public class TestParam { + public final int size; + public final int loops; + public TestParam(int size,int loops){ + this.size = size; + this.loops = loops; + } + public static TestParam[] array(int...values){ + int size = values.length/2; + TestParam[] result = new TestParam[size]; + int n = 0; + for(int i = 0;i { + public static int fieldWidth = 8; + public static TestParam[] defaultParams = TestParam.array(10,5000,100,5000,1000,5000,10000,500); + protected C initialize(int size){ + return container; + } + protected C container; + private String headline = ""; + private List> tests; + private static String stringFiled(){ + return "%"+fieldWidth+"s"; + } + private static String numberFiled(){ + return "%"+fieldWidth+"d"; + } + private static int sizeWidth = 5; + private static String sizeFiled = "%"+sizeWidth+"s"; + private TestParam[] paramList = defaultParams; + + public Tester(C container,List> tests){ + this.container = container; + this.tests = tests; + if(container != null){ + headline = container.getClass().getSimpleName(); + } + } + public Tester(C container,List> tests,TestParam[] paramList){ + this(container,tests); + this.paramList = paramList; + } + public void setHeadline(String newHeadline){ + this.headline = newHeadline; + } + public static void run(C cntnr,List> tests){ + new Tester(cntnr,tests).timedTest(); + } + public static void run(C cntnr,List> tests,TestParam[] paramList){ + new Tester(cntnr,tests,paramList).timedTest(); + } + private void displayHeader(){ + int width = fieldWidth * tests.size()+sizeWidth; + int dashLength = width-headline.length()-1; + StringBuilder head = new StringBuilder(width); + for(int i=0;i test:tests){ + C kontainer = initialize(param.size); + long start = System.nanoTime(); + int reps = test.test(kontainer, param); + long duration = System.nanoTime()-start; + long timePerRep = duration/reps; + System.out.format(numberFiled(), timePerRep); + } + System.out.println(); + } + } +} diff --git a/src/btp/oneP/TextFile.java b/src/btp/oneP/TextFile.java new file mode 100644 index 0000000..baa4acf --- /dev/null +++ b/src/btp/oneP/TextFile.java @@ -0,0 +1,83 @@ +package btp.oneP; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.TreeSet; + +@SuppressWarnings("serial") +public class TextFile extends ArrayList { + + public static String read(String fileName){ + StringBuilder sb = new StringBuilder(); + try{ + BufferedReader in = new BufferedReader(new FileReader(new File(fileName).getAbsoluteFile())); + try{ + String s; + while((s = in.readLine()) != null){ + sb.append(s); + sb.append("\n"); + } + }finally{ + in.close(); + } + }catch(IOException e){ + throw new RuntimeException(); + } + return sb.toString(); + } + + public static void write(String fileName,String text){ + try{ + PrintWriter out = new PrintWriter(new File(fileName).getAbsoluteFile()); + try{ + out.print(text); + }finally{ + out.close(); + } + }catch(IOException e){ + throw new RuntimeException(); + } + } + + public TextFile(String fileName,String splitter){ + super(Arrays.asList(read(fileName).split(splitter))); + if("".equals(get(0))){ + remove(0); + } + } + + public TextFile(String fileName){ + this(fileName,"\n"); + } + + public void write(String fileName){ + try{ + PrintWriter out = new PrintWriter(new File(fileName).getAbsoluteFile()); + try{ + for(String item : this){ + out.println(item); + } + }finally{ + out.close(); + } + }catch(IOException e){ + throw new RuntimeException(); + } + } + + public static void main(String[] args) { + String file = read("E:\\workspaces\\NewWork\\Study\\src\\btp\\oneP\\TextFile.java"); + System.out.println(file); + write("C:\\Users\\dell\\Desktop\\IO\\test.txt",file); + TextFile text = new TextFile("C:\\Users\\dell\\Desktop\\IO\\test.txt"); + text.write("C:\\Users\\dell\\Desktop\\IO\\test2.txt"); + TreeSet words = new TreeSet(new TextFile("E:\\workspaces\\NewWork\\Study\\src\\btp\\oneP\\TextFile.java","\\W+")); + System.out.println(words.headSet("a")); + } + +} diff --git a/src/btp/oneP/TrafficLight.java b/src/btp/oneP/TrafficLight.java new file mode 100644 index 0000000..b2f2851 --- /dev/null +++ b/src/btp/oneP/TrafficLight.java @@ -0,0 +1,27 @@ +package btp.oneP; + +public class TrafficLight { + Signal color = Signal.RED; + public void change(){ + switch(color){ + case RED:color = Signal.GREEN;break; + case GREEN:color = Signal.YELLOW;break; + case YELLOW:color = Signal.RED;break; + } + } + public String toString(){ + return "The traffic light is "+color; + } + public static void main(String[] args) { + TrafficLight t = new TrafficLight(); + for(int i = 0; i < 7;i++){ + System.out.println(t); + t.change(); + } + } + +} + +enum Signal{ + GREEN,YELLOW,RED +} diff --git a/src/btp/oneP/TransferTo.java b/src/btp/oneP/TransferTo.java new file mode 100644 index 0000000..e614c31 --- /dev/null +++ b/src/btp/oneP/TransferTo.java @@ -0,0 +1,20 @@ +package btp.oneP; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.channels.FileChannel; + +public class TransferTo { + + public static void main(String[] args) throws IOException { + FileChannel in = new FileInputStream("C:\\Users\\dell\\Desktop\\IO\\channelIn.txt").getChannel(), + out = new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\channelOut.txt").getChannel(); + System.out.println(in.size()); + //out.position(in.size()); + out.transferFrom(in, 0, in.size()); + //in.transferTo(0, in.size(), out); + } + +} diff --git a/src/btp/oneP/TypeOfFood.java b/src/btp/oneP/TypeOfFood.java new file mode 100644 index 0000000..84d5fc7 --- /dev/null +++ b/src/btp/oneP/TypeOfFood.java @@ -0,0 +1,17 @@ +package btp.oneP; + +import btp.oneP.Food.Appetizer; +import btp.oneP.Food.Coffee; +import btp.oneP.Food.DESSERT; +import btp.oneP.Food.MainCourse; + +public class TypeOfFood { + + public static void main(String[] args) { + Food food = Appetizer.SALAD; + food = MainCourse.LASAGNE; + food = DESSERT.GELATO; + food = Coffee.CAPPUCCINO; + } + +} diff --git a/src/btp/oneP/TypesForSets.java b/src/btp/oneP/TypesForSets.java index 4a3a6ac..b36285f 100644 --- a/src/btp/oneP/TypesForSets.java +++ b/src/btp/oneP/TypesForSets.java @@ -1,7 +1,9 @@ package btp.oneP; import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.Set; +import java.util.TreeSet; public class TypesForSets { static Set fill(Set set,Class type){ @@ -21,12 +23,23 @@ static void test(Set set,Class type){ } public static void main(String[] args) { test(new HashSet(),HashType.class); - test(new HashSet(),HashType.class); - test(new HashSet(),HashType.class); - test(new HashSet(),HashType.class); - test(new HashSet(),HashType.class); - test(new HashSet(),HashType.class); - test(new HashSet(),HashType.class); + test(new LinkedHashSet(),HashType.class); + test(new TreeSet(),TreeType.class); + test(new HashSet(),SetType.class); + test(new HashSet(),TreeType.class); + test(new LinkedHashSet(),SetType.class); + test(new LinkedHashSet(),TreeType.class); + try{ + test(new TreeSet(),SetType.class); + }catch(Exception e){ + System.out.println(e.getMessage()); + } + + try{ + test(new TreeSet(),HashType.class); + }catch(Exception e){ + System.out.println(e.getMessage()); + } } } diff --git a/src/btp/oneP/UpcastEnum.java b/src/btp/oneP/UpcastEnum.java new file mode 100644 index 0000000..9879398 --- /dev/null +++ b/src/btp/oneP/UpcastEnum.java @@ -0,0 +1,26 @@ +package btp.oneP; + +public class UpcastEnum { + + public static void main(String[] args) { + Search[] vals = Search.values(); + Enum e= Search.HITHER; + for(Enum en : e.getClass().getEnumConstants()){ + System.out.println(en); + } + + try{ + Class intClass = Integer.class; + for(Object en : intClass.getEnumConstants()){ + System.out.println(en); + } + }catch(Exception ee){ + ee.printStackTrace(); + } + } + +} + +enum Search{ + HITHER,YON +} diff --git a/src/btp/oneP/UsingBuffers.java b/src/btp/oneP/UsingBuffers.java new file mode 100644 index 0000000..a81648e --- /dev/null +++ b/src/btp/oneP/UsingBuffers.java @@ -0,0 +1,28 @@ +package btp.oneP; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; + +public class UsingBuffers { + private static void symmetricScramble(CharBuffer buff){ + while(buff.hasRemaining()){ + buff.mark(); + char c1 = buff.get(); + char c2 = buff.get(); + buff.reset(); + buff.put(c2).put(c1); + } + } + public static void main(String[] args) { + char[] data = "UsingBuffers".toCharArray(); + ByteBuffer bb = ByteBuffer.allocate(data.length * 2); + CharBuffer cb = bb.asCharBuffer(); + cb.put(data); + System.out.println(cb.rewind()); + symmetricScramble(cb); + System.out.println(cb.rewind()); + symmetricScramble(cb); + System.out.println(cb.rewind()); + } + +} diff --git a/src/btp/oneP/UsingRandomAccessFile.java b/src/btp/oneP/UsingRandomAccessFile.java new file mode 100644 index 0000000..823f451 --- /dev/null +++ b/src/btp/oneP/UsingRandomAccessFile.java @@ -0,0 +1,33 @@ +package btp.oneP; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; + +public class UsingRandomAccessFile { + static String file = "C:\\Users\\dell\\Desktop\\IO\\rtest.dat"; + + static void display() throws IOException{ + RandomAccessFile rf = new RandomAccessFile(file,"r"); + for(int i = 0;i < 7;i++){ + System.out.println("Value "+i+":"+rf.readDouble()); + } + System.out.println(rf.readUTF()); + rf.close(); + } + public static void main(String[] args) throws IOException { + RandomAccessFile rf = new RandomAccessFile(file,"rw"); + for(int i = 0;i < 7;i++){ + rf.writeDouble(i * 1.414); + } + rf.writeUTF("The end of the file"); + rf.close(); + display(); + rf = new RandomAccessFile(file,"rw"); + rf.seek(5 * 8); + rf.writeDouble(47.0001); + rf.close(); + display(); + } + +} diff --git a/src/btp/oneP/Utilities.java b/src/btp/oneP/Utilities.java new file mode 100644 index 0000000..f934aef --- /dev/null +++ b/src/btp/oneP/Utilities.java @@ -0,0 +1,62 @@ +package btp.oneP; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; +import java.util.Random; +import java.util.Vector; + +public class Utilities { + static List list = Arrays.asList("one two three four five six one".split(" ")); + public static void main(String[] args) { + System.out.println(list); + System.out.println("'list' disjoint (Four)?:"+Collections.disjoint(list, Collections.singletonList("four"))); + System.out.println("max:"+Collections.max(list)); + System.out.println("min:"+Collections.min(list)); + System.out.println("max w/ comparator:"+Collections.max(list,String.CASE_INSENSITIVE_ORDER)); + System.out.println("min w/ comparator:"+Collections.min(list,String.CASE_INSENSITIVE_ORDER)); + + List sublist = Arrays.asList("four five six".split(" ")); + System.out.println("indexOfSublist:"+Collections.indexOfSubList(list, sublist)); + System.out.println("lastIndexOfSublist:"+Collections.lastIndexOfSubList(list, sublist)); + + Collections.replaceAll(list, "one", "yo"); + System.out.println("replaceAll:"+list); + Collections.reverse(list); + System.out.println("reverse:"+list); + Collections.rotate(list, 3); + System.out.println("rotate:"+list); + + List source = Arrays.asList("in the matrix".split(" ")); + Collections.copy(list, source); + System.out.println("copy:"+list); + + Collections.swap(list, 0, list.size()-1); + System.out.println("swap:"+list); + + Collections.shuffle(list, new Random(47)); + System.out.println("shuffled:"+list); + + Collections.fill(list, "pop"); + System.out.println("fill:"+list); + + System.out.println("frequency of 'pop':"+Collections.frequency(list, "pop")); + + List dups = Collections.nCopies(3, "snap"); + System.out.println("dups:"+dups); + + System.out.println("'list' disjoint 'dups'?:"+Collections.disjoint(list, dups)); + + Enumeration e = Collections.enumeration(dups); + Vector v = new Vector(); + while(e.hasMoreElements()){ + v.addElement(e.nextElement()); + } + + ArrayList arrayList = Collections.list(v.elements()); + System.out.println("arrayList:"+arrayList); + } + +} diff --git a/src/btp/oneP/Value.java b/src/btp/oneP/Value.java new file mode 100644 index 0000000..a57c2fa --- /dev/null +++ b/src/btp/oneP/Value.java @@ -0,0 +1,10 @@ +package btp.oneP; + +public class Value extends Element { + + public Value(String id) { + super(id); + // TODO Auto-generated constructor stub + } + +} diff --git a/src/btp/oneP/VendingMachine.java b/src/btp/oneP/VendingMachine.java new file mode 100644 index 0000000..f3318de --- /dev/null +++ b/src/btp/oneP/VendingMachine.java @@ -0,0 +1,100 @@ +/*package btp.oneP; +import static btp.oneP.Input.ABORT_TRANSACTION; +import static btp.oneP.Input.CHIPS; +import static btp.oneP.Input.DIME; +import static btp.oneP.Input.DOLLAR; +import static btp.oneP.Input.NICKEL; +import static btp.oneP.Input.QUARTER; +import static btp.oneP.Input.SOAP; +import static btp.oneP.Input.SODA; +import static btp.oneP.Input.STOP; +import static btp.oneP.Input.TOOTHPASTE; + +import java.util.EnumMap; +public class VendingMachine { + private static State state = State.RESTING; + private static int amount = 0; + private static Input selection = null; + enum State{ + RESTING{ + void next(Input input){ + switch(Category.categorize(input)){ + case MONEY: + amount += input.amount(); + state = ADDING_MONEY; + break; + case SHUT_DOWN: + state = TERMINAL; + default: + } + } + }, + ADDING_MONEY{ + void next(Input input){ + switch(Category.categorize(input)){ + case MONEY: + amount += input.amount(); + break; + case ITEM_SELECTION: + selection = input; + if(amount < selection.amount()){ + System.out.print("Insufficient money for " + selection); + }else{ + state = DISPENSION; + } + break; + case QUIT_TRANSACTION: + state = GIVING_CHANGE; + break; + case SHUT_DOWN: + state = TERMINAL; + default: + } + } + }, + DISPENSING(StateDuration.TRANSIENT){ + void next(){ + + } + } + private boolean isTransient = false; + State(){} + State(StateDuration trans){ + isTransient = true; + } + void next(Input input){ + throw new RuntimeException("Only call next(Input input) for non-transient states"); + } + void next(){ + throw new RuntimeException("Only call next() for StateDuration.TRANSIENT states"); + } + void output(){ + System.out.print(amount); + } + } +} + +enum Category{ + MONEY(NICKEL,DIME,QUARTER,DOLLAR), + ITEM_SELECTION(TOOTHPASTE,CHIPS,SODA,SOAP), + QUIT_TRANSACTION(ABORT_TRANSACTION), + SHUT_DOWN(STOP); + + private Input[] values; + Category(Input...types){ + this.values = types; + } + + private static EnumMap categories = new EnumMap(Input.class); + + static{ + for(Category c : Category.class.getEnumConstants()){ + for(Input type : c.values){ + categories.put(type, c); + } + } + } + public static Category categorize(Input input){ + return categories.get(input); + } +}*/ \ No newline at end of file diff --git a/src/btp/oneP/VeryBig.java b/src/btp/oneP/VeryBig.java new file mode 100644 index 0000000..ba449aa --- /dev/null +++ b/src/btp/oneP/VeryBig.java @@ -0,0 +1,16 @@ +package btp.oneP; + +public class VeryBig { + private static final int SIZE = 10000; + private long[] la = new long[SIZE]; + private String ident; + public VeryBig(String id){ + this.ident = id; + } + public String toString(){ + return ident; + } + protected void finalize(){ + System.out.println("Finalizing "+ident); + } +} diff --git a/src/btp/oneP/ViewBuffers.java b/src/btp/oneP/ViewBuffers.java new file mode 100644 index 0000000..5222de0 --- /dev/null +++ b/src/btp/oneP/ViewBuffers.java @@ -0,0 +1,58 @@ +package btp.oneP; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.DoubleBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.nio.LongBuffer; +import java.nio.ShortBuffer; + +public class ViewBuffers { + + public static void main(String[] args) { + ByteBuffer bb = ByteBuffer.wrap(new byte[]{0,0,0,0,0,0,0,'a'}); + bb.rewind(); + System.out.print("Byte Buffer "); + while(bb.hasRemaining()){ + System.out.print(bb.position()+" -> "+bb.get()+","); + } + System.out.println(); + CharBuffer cb = ((ByteBuffer)bb.rewind()).asCharBuffer(); + System.out.print("Char Buffer "); + while(cb.hasRemaining()){ + System.out.print(cb.position()+" -> "+cb.get()+","); + } + System.out.println(); + FloatBuffer fb = ((ByteBuffer)bb.rewind()).asFloatBuffer(); + System.out.print("Float Buffer "); + while(fb.hasRemaining()){ + System.out.print(fb.position()+" -> "+fb.get()+","); + } + System.out.println(); + IntBuffer ib = ((ByteBuffer)bb.rewind()).asIntBuffer(); + System.out.print("Int Buffer "); + while(ib.hasRemaining()){ + System.out.print(ib.position()+" -> "+ib.get()+","); + } + System.out.println(); + LongBuffer lb = ((ByteBuffer)bb.rewind()).asLongBuffer(); + System.out.print("Long Buffer "); + while(lb.hasRemaining()){ + System.out.print(lb.position()+" -> "+lb.get()+","); + } + System.out.println(); + ShortBuffer sb = ((ByteBuffer)bb.rewind()).asShortBuffer(); + System.out.print("Short Buffer "); + while(sb.hasRemaining()){ + System.out.print(sb.position()+" -> "+sb.get()+","); + } + System.out.println(); + DoubleBuffer db = ((ByteBuffer)bb.rewind()).asDoubleBuffer(); + System.out.print("Float Buffer "); + while(db.hasRemaining()){ + System.out.print(db.position()+" -> "+db.get()+","); + } + } + +} diff --git a/src/btp/oneP/Worm.java b/src/btp/oneP/Worm.java new file mode 100644 index 0000000..371d715 --- /dev/null +++ b/src/btp/oneP/Worm.java @@ -0,0 +1,79 @@ +package btp.oneP; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.Random; + +public class Worm implements Serializable{ + private static Random rand = new Random(47); + private Data[] d = { + new Data(rand.nextInt(10)), + new Data(rand.nextInt(10)), + new Data(rand.nextInt(10)) + }; + private Worm next; + private char c; + public Worm(int i,char x){ + System.out.println("Worm constructor:"+i); + c = x; + if(--i > 0){ + next = new Worm(i,(char)(x+1)); + } + } + public Worm(){ + System.out.println("Default constructor"); + } + public String toString(){ + StringBuilder sb = new StringBuilder(":"); + sb.append(c); + sb.append("("); + for(Data dat : d){ + sb.append(dat); + } + sb.append(")"); + if(null != next){ + sb.append(next); + } + return sb.toString(); + } + public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { + Worm w = new Worm(6,'a'); + System.out.println("w = "+w); + ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\worm.out")); + out.writeObject("Worm storage\n"); + out.writeObject(w); + out.close(); + ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:\\Users\\dell\\Desktop\\IO\\worm.out")); + String s = (String)in.readObject(); + Worm w2 = (Worm)in.readObject(); + System.out.println(s + "w2 = "+w2); + + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream out2 = new ObjectOutputStream(bout); + out2.writeObject("Worm storage\n"); + out2.writeObject(w); + out2.flush(); + ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray())); + s = (String)in2.readObject(); + Worm w3 = (Worm)in2.readObject(); + System.out.println(s + "w3 = "+w3); + } + +} + +class Data implements Serializable{ + private int n; + public Data(int n){ + this.n = n; + } + public String toString(){ + return Integer.toString(n); + } +} diff --git a/src/btp/oneP/ZipCompres.java b/src/btp/oneP/ZipCompres.java new file mode 100644 index 0000000..015a768 --- /dev/null +++ b/src/btp/oneP/ZipCompres.java @@ -0,0 +1,68 @@ +package btp.oneP; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.util.Enumeration; +import java.util.zip.Adler32; +import java.util.zip.CheckedInputStream; +import java.util.zip.CheckedOutputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + +public class ZipCompres { + + public static void main(String[] args) throws IOException { + FileOutputStream f = new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\test.zip"); + CheckedOutputStream csum = new CheckedOutputStream(f,new Adler32()); + ZipOutputStream zos = new ZipOutputStream(csum); + BufferedOutputStream out = new BufferedOutputStream(zos); + zos.setComment("A test of Java Zipping"); + String[] adds = {"C:\\Users\\dell\\Desktop\\IO\\channelIn.txt","C:\\Users\\dell\\Desktop\\IO\\channelOut.txt","C:\\Users\\dell\\Desktop\\IO\\Data.txt","C:\\Users\\dell\\Desktop\\IO\\data2.txt"}; + for(String s:adds){ + System.out.println("Writing file"); + BufferedReader in = new BufferedReader(new FileReader(s)); + zos.putNextEntry(new ZipEntry(s)); + int c; + while((c = in.read()) != -1){ + out.write(c); + } + in.close(); + out.flush(); + } + + out.close(); + System.out.println("Checksum: "+csum.getChecksum().getValue()); + + System.out.println("Reading file"); + FileInputStream fi = new FileInputStream(new File("C:\\Users\\dell\\Desktop\\IO\\test.zip")); + CheckedInputStream csumi = new CheckedInputStream(fi,new Adler32()); + ZipInputStream in2 = new ZipInputStream(csumi); + BufferedInputStream bis = new BufferedInputStream(in2); + ZipEntry ze; + while((ze = in2.getNextEntry()) != null){ + System.out.println("Reading file "+ze); + int x; + while((x = bis.read()) != -1){ + System.out.print(x); + } + } + bis.close(); + System.out.println("--------------------"); + ZipFile zf = new ZipFile("C:\\Users\\dell\\Desktop\\IO\\test.zip"); + Enumeration e = zf.entries(); + while(e.hasMoreElements()){ + ZipEntry ze2 = e.nextElement(); + System.out.println(ze2); + } + + } + +}