【发布时间】:2018-01-26 13:02:35
【问题描述】:
我将 Singly_Linked_List 与泛型一起使用并存储类循环对象,并且循环只有一个参数价格,因此 getElement() 将返回价格。但是 list.contains(walk.getElement()) 总是返回 false。我在 toString 方法中遇到了麻烦。下面给出整个实现。
public String toString() {
ArrayList<E> list = new ArrayList<>();
Node<E> walk = head;
while (walk != null) {
if (!list.contains(walk.getElement()))
list.add(walk.getElement());
walk = walk.getNext();
}
return list.toString();
}
整个列表实现:
import java.util.ArrayList;
public class Singly_Linked_List<E> {
class Node<E> {
private E element;
private Node<E> next;
Node(E element, Node<E> next) {
this.element = element;
this.next = next;
}
void setNext(Node<E> next) {
this.next = next;
}
E getElement() {
return element;
}
Node<E> getNext() {
return next;
}
}
private Node<E> tail;
private Node<E> head;
private int size = 0;
Singly_Linked_List() {
}
int getSize() {
return size;
}
boolean isEmpty() {
return getSize() == 0;
}
void addFirst(E element) {
head = new Node<E>(element, head);
if (isEmpty())
tail = head;
size++;
}
void addLast(E element) {
Node<E> node = new Node<E>(element, null);
if (isEmpty())
head = node;
else
tail.setNext(node);
tail = node;
size++;
}
E first() {
if (isEmpty())
return null;
return head.getElement();
}
E last() {
if (isEmpty())
return null;
return tail.getElement();
}
E removeFirst() {
if (isEmpty()) return null;
E answer = head.getElement();
head = head.getNext();
if (head == tail)
tail = null;
size--;
return answer;
}
@Override
public String toString() {
ArrayList<E> list = new ArrayList<>();
Node<E> walk = head;
while (walk != null) {
if (!list.contains(walk.getElement()))
list.add(walk.getElement());
walk = walk.getNext();
}
return list.toString();
}
}
循环类实现:
public class Cycle{
private int price;
Cycle(int price) {
this.price = price;
}
int getPrice() {
return this.price;
}
@Override
public String toString() {
return "" + this.price;
}
public boolean equals(Cycle cycle) {
return this.getPrice() == cycle.getPrice();
}
}
【问题讨论】:
-
请显示对象并列出实现。
-
list为空。为什么它会包含一些东西? -
getElement()返回什么类型?可能是自定义类没有正确实现equals()? -
@jsheeran,第一次是空的,之后就不会空了
-
@IanMc,顺序无关紧要,它应该是唯一的。如果我要删除或添加唯一元素,list.size() 将根据驱动程序方法发生变化。
标签: java generics singly-linked-list