tailieunhanh - Object Oriented Programming using Java phần 9

Những tuyên bố thử đầu tiên để đảm bảo rằng chúng tôi thậm chí không cố gắng để giao tiếp qua mạng trừ khi chúng tôi đã thành công mở ra một kết nối. Giả trong ví dụ này sau một mô hình chung có thể được sử dụng để có được một nguồn tài nguyên mạnh mẽ, sử dụng tài nguyên, và sau đó phát hành các tài nguyên. | public class Card Class to represent playing cards. int suit Number from 0 to 3 that codes for the suit spades diamonds clubs or hearts. int value Number from 1 to 13 that represents the value. public boolean equals Object obj try Card other Card obj Type-cast obj to a Card. if suit value The other card has the same s uit and value as this card so they should be considered equal. return true else return false catch Exception e This will catch the NullPointerException that occurs if obj is null and the ClassCastException that occurs if obj is not of type Card. In these cases obj is not equal to this Card so return false . return false . other methods and constructors . A similar concern arises when items in a collection are sorted. Sorting refers to arranging a sequence of items in ascending order according to some criterion. The problem is that there is no natural notion of ascending order for arbitrary objects. Before objects can be sorted some method must be defined for comparing them. Objects that are meant to be compared should implement the interface . In fact Comparable is defined as a parameterized interface Comparable T which represents the ability to be compared to an object of type T. The interface Comparable T defines one method public int compareTo T obj . The value returned by obj2 should be negative if and only if obj1 comes before obj2 when the objects are arranged in ascending order. It should be positive if and only if obj1 comes after obj2. A return value of zero means that the objects are considered to be the same for the purposes of this comparison. This does not necessarily mean that the objects are equal in the sense that obj2 is true. For example if the objects are of type Address representing mailing addresses it might be useful to sort the objects by zip code. Two Addresses are considered the same for the purposes of the sort if they have the same zip code-but clearly .

TỪ KHÓA LIÊN QUAN