State 模式在客L软g中的应用
在对一?J2EE 目的重构、增加新功能的过E中Q对客户?GUI E序Q我们用了 State 模式。结果显C,该模式的使用Q不但减了客户?GUI E序的程序规模(LOCQ,而且Q该部分的开发及单元试旉大大减少Q同Ӟ在集成测试中发现的缺h量比使用该模式前q_减少?倍。本文就该项目中使用 State 模式的方式进行介l?
State 模式在客L软g中的应用
在对一?J2EE 目的重构、增加新功能的过E中Q对客户?GUI E序Q我们用了 State 模式。结果显C,该模式的使用Q不但减了客户?GUI E序的程序规模(LOCQ,而且Q该部分的开发及单元试旉大大减少Q同Ӟ在集成测试中发现的缺h量比使用该模式前q_减少?倍。本文就该项目中使用 State 模式的方式进行介l?
内嵌cInner Class)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1.内嵌cd以访问outercȝM变量,包括U有?
2.静态innerc?只能讉KoutercȝMstatic变量
2.1内嵌cd以是final,abstract?br />
3.我靠,Ҏ内的内嵌cM能ؓstatic: void test(){ static class A{}} XXXXX!!!!
4.我靠,Ҏ内的内嵌cM不能带Q何modifier,void test(){ public class A{}} XXXXX!!!!
5.我靠,Ҏ内的内嵌cd能访问方法内的final变量,但是,可以讉KoutercȝM变量.
6.匿名cM能有构造器,但声明时候带参数,相当于构造器的参C?
class ABC{}
class ABCD{private ABCD(int i){}}
ABC test3(){return new ABC(){};}
ABCD test4(){return new ABCD(3){};}
interface iii{}
iii test5(){return new iii(){};}
//class BCD extends ABCD{} compile error,因ؓ,
看上面就知道,new iii(){};实际上匿名类实现了iii接口;new ABC(){};实际上是匿名cȝ承了ABC.
8.
class A {private A(){System.out.println("a!");}}
class B extends A{}
我靠,没错!B实例的时候会d调用父类A的构?即是private?看来也没问题!!!
9.内部cd以有synchronizedҎ,那么锁是q个内部c?跟外部类没一点关p?内外分别?在锁的问题上.
10.外部cM能通过this被访?thisq时候应该指的是内部c?享用外部cȝ成员q接用,不用加Q何限定词
11.如何用this呢请?
class Outer{ int i;
class Inner{
class InnerInner{
void Test(){
Outer.this.i=1;
}
}
}
}
看见了吧,cd.this.变量?可以引用到i,W一ơ看到吧,嘿嘿,孤陋寡闻.
12.注意q两U写法都可以
Class Outer.Inner i = new Outer().new Inner();
或? Class o= new Outer(); Class Outer.Inner i=o.new Inner();
变量修饰W?Modifier)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1.最外面一层的cM能声明成protect和pravite?br />
2.同一个类的两个实例之间可以访问彼此的U有Ҏ和私有变??br />
3.protect和无修饰W的具体区别关于外包可以讉K被子c访问的是哪?br />
4.成员变量被修饰成final?必须声明时候就赋初值或者在构造器里面赋初?别指望她可以得到default?
5.抽象Ҏ不能是static?!!
6.静态方法将随着cȝ变化而变?看例?
class Parent{
static void test(){System.out.println("hi,parent")};
}
class Child extends Parent{
static void test(){System.out.println("hi,child")};
}
Parent p = new Child();
p.test(); //打出来的是hi,parent!
7.静态方法可以通过cȝ实例调用.
new Child().test(); ?Child.test(); 都OK!
8.transient只能用在cȝ成员变量?不能用在Ҏ?
9.transient变量不能是final和static?br />
10.nativeҎ可以是private,abstractd?/p>
程控制
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1。不可到辄语句声明为错Qwhile(false){} ;for(;false{};if(false){}都无法编?br />
2。for(W一部分;的第一部分可以用来声明或者赋|但不能两者都
3。byte b; switch { case 200: // 200 not in range of byteQ因?00过b的范_编译错?br />
4。带标签的continue回达到标{位置Q从新进入紧接在标签后面的@?br />
5。带标签的break会中断当前@环,q{Ud标签标示的的循环的末?/p>
转型和上?Converting and Casting)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Binary operators convert the smaller(less precise) operand to the type of the larger(more precise) operand.
All operators will convert things smaller than ints to ints or larger. This includes char 's!
1.byte,char,short默认转成int
2.byte->short->int->long->float->double
char^
q是默认可以转型的方?反了必须要显式cast! 特别注意:long->float是默认的,别看long64,float32,嘿嘿
q有是看得出来,char?byte,short之间无法互相默认转换
3.float f=1/3; OK!float f=1.0/3.0;~译出错,因ؓ1.0/3.0l果是double?噢噢~,错喽!!
4.int i=1; byte b=i;?需要显式cast.
final i=1; byte b=i;ok! 我也不知道ؓ什?final可?而且,据我实验只有int和byte的关p这?其他不行.
5.int i[]; Object[] obj=i;? Object obj=i;? 数组只能转成Object,而不能是Object[]
6.int i[]; Object[] obj;i=(int[])obj; ? 对象可以通过昑ּ来{成一个数l?
expression_r1是一条被判断的布表辑ּQ必M证在E序执行q程中它的g定是真;expression_r2是可选的Q用于在expression_r1为假Ӟ传递给抛出的异常AssertionError的构造器Q因此expression_r2的类型必L合法的AssertionError构造器的参数类型。AssertionError除了一个不带参数的~省构造器外,q有7个带单个参数的构造器Q分别ؓQobjectQeg.StringQ? boolean char int long float double。第一UŞ式如果抛出异常,则调用AssertionError的缺省构造器Q对于第二种形式Q则Ҏexpression_r2值的cdQ分别调?U单参数构造器中的一U?/p>
]]>W九部分Q集合类框架http://www.tkk7.com/balajinima/articles/298540.html李云?/dc:creator>李云?/author>Fri, 16 Oct 2009 03:44:00 GMThttp://www.tkk7.com/balajinima/articles/298540.htmlhttp://www.tkk7.com/balajinima/comments/298540.htmlhttp://www.tkk7.com/balajinima/articles/298540.html#Feedback0http://www.tkk7.com/balajinima/comments/commentRss/298540.htmlhttp://www.tkk7.com/balajinima/services/trackbacks/298540.htmlW九部分Q集合类框架
知道如何在特定的条g下选择适合的集合类/接口?
能正地实现hashcodeҎ?
W一?nbsp; 所有接口和class定义
1:Set
public interface Set extends Collection
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
2:SortedSet
public interface SortedSet extends Set.
A set that further guarantees that its iterator will traverse the set in ascending element order, sorted according to the natural ordering of its elements (see Comparable), or by a Comparator provided at sorted set creation time.
3:HashSet
public class HashSet extends AbstractSet implements Set, Cloneable, Serializable
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
4:TreeSet
public class TreeSet extends AbstractSet implements SortedSet, Cloneable, Serializable
This class implements the Set interface, backed by a TreeMap instance. This class guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements (see Comparable), or by the comparator provided at set creation time, depending on which constructor is used.
5:LinkedHashSet:
public class LinkedHashSet extends HashSet implements Set, Cloneable, Serializable
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)
5:Map
public interface Map
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
6:SortedMap
public interface SortedMap extends Map
A map that further guarantees that it will be in ascending key order, sorted according to the natural ordering of its keys (see the Comparable interface), or by a comparator provided at sorted map creation time. (This interface is the map analogue of the SortedSet interface.)
7:HashMap(允许key和value为NULL)
public class HashMap extends AbstractMap implements Map, Cloneable, Serializable
Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time
8:TreeMap
public class TreeMap extends AbstractMap implements SortedMap, Cloneable, Serializable
Red-Black tree based implementation of the SortedMap interface. This class guarantees that the map will be in ascending key order, sorted according to the natural order for the key's class (see Comparable), or by the comparator provided at creation time, depending on which constructor is used.
9:HashTable(不允许key和value为NULL)
public class Hashtable extends Dictionary implements Map, Cloneable, Serializable.
This class implements a hashtable, which maps keys to values. Any non-null object can be used as a key or as a value.
9:LinkedHashMap
public class LinkedHashMap extends HashMap
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)
9:IdentityHashMap
public class IdentityHashMap extends AbstractMap implements Map, Serializable, Cloneable
This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).)
This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.
10:List
public interface List extends Collection
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all.
11:ArrayList
public class ArrayList extends AbstractList implements List, Cloneable, Serializable
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)
12:LinkedList
public class LinkedList extends AbstractSequentialList implements List, Cloneable, Serializable
Linked list implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface, the LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue (deque).
13:Vector
public class Vector extends AbstractList implements List, Cloneable, Serializable
The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.
14:Collection
public interface Collection
The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The SDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.
15:Collections
public class Collections extends Object
This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.
What will happen when you attempt to compile and run the following code?
class MyThread extends Thread
{
public void run()
{
System.out.println("MyThread: run()");
}
public void start()
{
System.out.println("MyThread: start()");
}
}
class MyRunnable implements Runnable
{
public void run()
{
System.out.println("MyRunnable: run()");
}
public void start()
{
System.out.println("MyRunnable: start()");
}
}
public class MyTest
{
public static void main(String args[])
{
MyThread myThread = new MyThread();
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
myThread.start();
thread.start();
}
}
Choices:
a. Prints : MyThread: start() followed by MyRunnable:run()
b. Prints : MyThread: run() followed by MyRunnable:start()
c. Prints : MyThread: start() followed by MyRunnable:start()
d. Prints : MyThread: run() followed by MyRunnable:run()
e. Compile time error
f. None of the above
――――――――――――――?/p>
A is the correct choice. In the above code there is not any compilation error. Thus choice E is incorrect. Inside main() method, objects of MyThread and MyRunnable class are created followed by creation of Thread with object of MyRunnable class. Note that MyThread class extends Thread class and overrides the start() method of the Thread class. Thus on execution of "myThread.start()" statement, the start() method of the MyThread class will be executed and as a result "MyThread:start()" will be printed. Had the start() method not there in MyThread class, the start() method of the Thread class would be called which in turn would call the run() method of the MyThread class. On execution of "thread.start();", the start() method of the Thread class would be called which in turn will call the run() method of the class which is passed to Thread constructor (i.e. MyRunnable class). Thus "MyRunnable:run()" will be printed out. Thus choice A is correct.
What will be the output on compiling/running the following code?
public class MyThread implements Runnable
{
String myString = "Yes ";
public void run()
{
this.myString = "No ";
}
public static void main(String[] args)
{
MyThread t = new MyThread();
new Thread(t).start();
for (int i=0; i < 10; i++)
System.out.print(t.myString);
}
}
Choices:
a. Compilation Error
b. Prints : Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes and so on.
c. Prints : No No No No No No No No No No and so on.
d. Prints : Yes No Yes No Yes No Yes No Yes No and so on.
e. The Output cannot be determined.
E is correct. Please note that there will not be any compilation error when the above code is compiled. Also note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operation system and other running threads, the thread on which start is called will get executed. In the above case it is not guaranteed that the thread will be executed(i.e. run() method will be called), always before "for" loop is executed. Thus the output cannot be determined.
Multiple objects of MyClass (given below) are used in a program that uses
multiple Threadsto create new integer count. What will happen when other threads
use the following code?
class MyClass
{
static private int myCount = 0;
int yourNumber;
private static synchronized int nextCount()
{
return ++myCount;
}
public void getYourNumber()
{
yourNumber = nextCount();
}
}
Choices:
a. The code will give compilation error.
b. The code will give runtime error.
c. Each thread will get a unique number.
d. The uniqueness of the number among different Threads can't be guaranteed.
――――――――――――?/p>
C is correct. The use of synchronized ensures that the number generated will not be duplicated, no matter how many Threads are trying to create the number. Thus D is incorrect. A and B are incorrect as the above code will not give any compiletime or runtime error.
What will happen when you attempt to compile and run the following code?
public class MyThread extends Thread
{
String myName;
MyThread(String name)
{
myName = name;
}
public void run()
{
for(int i=0; i<100;i++)
{
System.out.println(myName);
}
}
public static void main(String args[])
{
try
{
MyThread mt1 = new MyThread("mt1");
MyThread mt2 = new MyThread("mt2");
mt1.start();
// XXX
mt2.start();
}
catch(InterruptedException ex)
{
}
}
}
Choices:
a.The above code in its current condition will not compile.
b. In order to make the MyThread class prints "mt1" (100 times) followed by
"mt2" (100 times), mt1.join(); can be placed at //XXX position.
c. In order to make the MyThread class prints "mt1" (100 times) followed by
"mt2" (100 times), mt1.sleep(100); can be placed at //XXX position.
d. In order to make the MyThread class prints "mt1" (100 times) followed by
"mt2" (100 times), mt1.run(); can be placed at //XXX position.
e. In order to make the MyThread class prints "mt1" (100 times) followed by
"mt2" (100 times), there is no need to write any code.
―――――――――――――?/p>
A and B are correct. In its current condition, the above code will not compile as "InterruptedException" is never thrown in the try block. The compiler will give following exception: "Exception java.lang.InterruptedException is never thrown in the body of the corresponding try statement." Note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operating system and other running threads, the thread on which start is called will get executed. After making the above code to compile (by changing the InterruptedException to some other type like Exception), the output can't be predicted (the order in which mt1 and mt2 will be printed can't be guaranteed). In order to make the MyThread class prints "mt1" (100 times) followed by "mt2" (100 times), mt1.join() can be placed at //XXX position. The join() method waits for the Thread on which it is called to die. Thus on calling join() on mt1, it is assured that mt2 will not be executed before mt1 is completed. Also note that the join() method throws InterruptedException, which will cause the above program to compile successfully. Thus choice A and B are correct.
What will happen when you attempt to compile and run the following code?
public class MyThread extends Thread{
String myName;
MyThread(String name){
myName = name;
}
public void run(){
for(int i=0; i<100;i++){
System.out.println(myName);
}
}
public static void main(String args[]){
try{
MyThread mt1 = new MyThread("mt1");
MyThread mt2 = new MyThread("mt2");
mt1.start();
// XXX
mt2.start();
}catch(InterruptedException ex){}
}
}
A. compile error
B. mt1.join();
C. mt1.sleep(100);
D. mt1.run()
E. nothing need
Choice A and B are correct. In its current condition, the above code will not compile as "InterruptedException" is never thrown in the try block. The compiler will give following exception: "Exception java.lang.InterruptedException is never thrown in the body of the corresponding try statement."
Note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operating system and other running threads, the thread on which start is called will get executed. After making the above code to compile (by changing the InterruptedException to some other type like Exception), the output can't be predicted (the order in which mt1 and mt2 will be printed can't be guaranteed). In order to make the MyThread class prints "mt1" (100 times) followed by "mt2" (100 times), mt1.join() can be placed at //XXX position. The join() method waits for the Thread on which it is called to die. Thus on calling join() on mt1, it is assured that mt2 will not be executed before mt1 is completed. Also note that the join() method throws InterruptedException, which will cause the above program to compile successfully. Thus choice A and B are correct.
Multiple objects of MyClass (given below) are used in a program that uses multiple Threads to create new integer count. What will happen when other threads use the following code?
class MyClass{
static private int myCount = 0;
int yourNumber;
private static synchronized int nextCount(){
return ++myCount; //myCount为static
}
public void getYourNumber(){
yourNumber = nextCount();
}
}
A. the code ill give ompilation error
B. the code ill give runtime error
C. each thread will get a unique number
D. the uniqueness of the number different Threads can’t be guaranteed.
C is correct. The use of synchronized ensures that the number generated will not be duplicated, no matter how many Threads are trying to create the number. Thus D is incorrect. A and B are incorrect as the above code will not give any compiletime or runtime error.
What will be the output on compiling/running the following code?
public class MyThread implements Runnable {
String myString = "Yes ";
public void run() {
this.myString = "No ";
}
public static void main(String[] args) {
MyThread t = new MyThread();
new Thread(t).start();
for (int i=0; i < 10; i++)
System.out.print(t.myString);
}
}
A. compile error
B. prints: yes yes yes yes yes yes and so on
C. prints: no no no no no no no no and so on
D. prints: yes no yes no ye no ye no and so on
E. the output cannot be determinated
E is correct. Please note that there will not be any compilation error when the above code is compiled. Also note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operation system and other running threads, the thread on which start is called will get executed. In the above case it is not guaranteed that the thread will be executed(i.e. run() method will be called), always before "for" loop is executed. Thus the output cannot be determined.