我試圖從鏈表中刪除一個實例,但是當我嘗試搜索列表中的對象時,它返回值-1,因爲它說不存在。我究竟做錯了什麼。我的應用程序類之下,而且要求在我的DataSet類從正在使用對的鏈表中刪除一個實例
public class Application {
public static void main(String[] args) {
DataSet<String, Integer> db = new DataSet<>();
db.add("Theo", 4);
db.add("Maria", 5);
db.add("Adam", 4);
db.add("James", 5);
db.add("Charles", 7);
db.add("Nikki", 5);
db.add("Lynne", 5);
db.add("Kendal", 6);
db.add("Kerry", 5);
db.add("Janet", 5);
db.add("Gordon", 6);
db.add("Stepher", 7);
db.add("Sue", 3);
db.add("Ed", 2);
db.add("Adam", 4);
db.displayItems();
/*
System.out.println();
db.sortByFirst();
db.displayItems();
System.out.println();
db.sortBySecond();
db.displayItems();
System.out.println();
(db.findBySecond(5)).displayItems();
System.out.println();
(db.findByFirst("Adam")).displayItems();
System.out.println();
*/ System.out.println(db.remove("Adam", 4));
db.displayItems();
//System.out.println("size = " + db.size());
}
}
的方法和數據集是:
import java.util.LinkedList;
/**
*
* @param <T>
* @param <S>
*/
public class DataSet<T, S> {
LinkedList<Pair> datastructure = new LinkedList<>();
// Adds a new instance/item to the data structure.
public void add(T first, S second) {
Pair p = new Pair(first, second);
datastructure.add(p);
}
// Displays all itmes in the data structure.
public void displayItems() {
for (int i = 0; i < datastructure.size(); i++) {
System.out.println(datastructure.get(i));
}
}
// Removes all instances with matching criteria (first and second attribute values) and returns the number of instances removed.
public int remove(T first, S second) {
int count = 0;
Pair p = new Pair(first, second);
for (Pair datastructure1 : datastructure) {
Integer num = datastructure.indexOf(p);
System.out.println(num);
Boolean removed = datastructure.remove(p);
System.out.println(removed);
}
//will return count of how many removed
return count;
}
}
和最後一類是對類
class Pair<T,S> {
private T first;
private S second;
public Pair(T theFirst, S theSecond) {
first = theFirst;
second = theSecond;
}
public T getFirst() {
return first;
}
public S getSecond() {
return second;
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}