@w1024020103
2017-02-16 13:31
字数 1749
阅读 1973
CS61B
UCBerkeley
java
When writing LinkedListDeque.java
, I ran into some prolems. The given API says things like:
public void addFirst(Item): Adds an item to the front of the Deque.
public void addLast(Item): Adds an item to the back of the Deque.
I didn't get what does Item
mean here, should I just write exactly Item
or should I replace it withString
or int
?
I got compiler errors when I wrote Item
, so I replaced it with String
since the LinkedListDequeTest.java
first created a new LinkedListDeque of strings(line 40).
However, I got compiler error again as follows:
Then I asked people in wechat study group for help, and they helped me out with this problem. I added<Item>
after the class name to meet the requested generic type as follows:
public class LinkedListDeque<Item>{
private class Node<Item>{
Item item;
Node next, prev;
But this is not enough, I had to add<Item>
to other places as well:
private int size;
private Node <Item> sentinel, last;
public <Item> Item removeFirst(){
if(sentinel.next == null){
return null;
}
Item item = <Item> sentinel.next.item;
sentinel.next = sentinel.next.next;
size -= 1;
return item;
}
public <Item> Item removeLast(){
Item item = (Item)last.item;
last = last.prev;
last.next = sentinel;
size -= 1;
return item;
}
Seems like I added <Item>
to every related class and method, especially I used (Item)
for casting. This caused a whitle and finally got some help from the wechat study group.
Later, I was stuck by a problem:
I searched the webs for help, most of the talks were about mistakes in the number of }
, some were about GBK and UTF-8. Ironcally, I spent almost half a day finding where went wrong but in vain. Looking back, i guess i was just pissed off and didn't have patience. So, this is a good practice when you are faced with a unknown problem, just stay patient and carefully analyze it.
It turned out I added an extra }
when testing parts of the program, and I forgot to delete it when wrote some new parts.
Great, finally things went on well.
I ran into problems when writing resize() method for ArrayDeque.java.