Đang chuẩn bị liên kết để tải về tài liệu:
Thinking in Java 4th Edition phần 4

Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ

Phương pháp loại bỏ () là một "hoạt động tùy chọn," mà bạn sẽ tìm hiểu về các thùng chứa trong chương Độ sâu. Ở đây, không cần thiết để thực hiện nó, và nếu bạn gọi nó, nó sẽ ném ra một ngoại lệ. Từ ví dụ này, bạn có thể thấy rằng nếu bạn thực hiện | Simpo PDF Merge and Split Unregistered Version - http www.simpopdf.com public static void main String args Collectionsequence c new CollectionSequence InterfaceVslterator.display c InterfaceVsIterator.display c.iterator . . Output 0 Rat 1 Manx 2 Cymric 3 Mutt 4 Pug 5 Cymric 6 Pug 7 Manx 0 Rat 1 Manx 2 Cymric 3 Mutt 4 Pug 5 Cymric 6 Pug 7 Manx The remove method is an optional operation which you will learn about in the Containers in Depth chapter. Here it s not necessary to implement it and if you call it it will throw an exception. From this example you can see that if you implement Collection you also implement iterator and just implementing iterator alone requires only slightly less effort than inheriting from AbstractCoUection. However if your class already inherits from another class then you cannot also inherit from Abstractcollection. In that case to implement Collection you d have to implement all the methods in the interface. In this case it would be much easier to inherit and add the ability to create an iterator holding NonCollectionSequence.java import typeinfo.pets. import java.util. class PetSequence protected Pet pets Pets.createArray 8 public class NonCollectionSequence extends PetSequence public Iterator Pet iterator return new Iterator Pet private int index 0 public boolean hasNext return index pets.length public Pet next return pets index public void remove Not implemented throw new UnsupportedOperationException . public static void main String args NonCollectionSequence nc new NonCollectionSequence InterfaceVsIterator.display nc.iterator . . Output 0 Rat 1 Manx 2 Cymric 3 Mutt 4 Pug 5 Cymric 6 Pug 7 Manx Producing an Iterator is the least-coupled way of connecting a sequence to a method that consumes that sequence and puts far fewer constraints on the sequence class than does implementing Collection. Exercise 30 5 Modify CollectionSequence.java so that it does not inherit from AbstractCollection but instead implements Collection. Holding Your .