我是Java的新手,所以我几乎不知道如何解决这个问题。我对链表和数组列表都工作正常,我是HashSet的新手,所以我不确定这是否是导致错误的原因。这是我收到错误的地方:
return (Object) subList.get(row).getSName();
return (Object) subList.get(row).getNumMonths();
错误会不断在get中加下划线。它说:
Cannot find Symbol
symbol:method get(int)
location: variable subList of type HashSet <Sub>
这里是引发错误的类:
public class SubTableModel extends AbstractTableModel {
private String[] columnsNames = {"Subscription Name", "# of months Subbed"};
private HashSet<Sub> subList;
public SubTableModel(HashSet<Sub> newSubList) {
subList = newSubList;
}
@Override
public int getRowCount() {
return subList.size();
}
@Override
public int getColumnCount() {
return columnsNames.length;
}
@Override
public String getColumnName(int col) {
return columnsNames[col];
}
@Override
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return (Object) subList.get(row).getSName();
case 1:
return (Object) subList.get(row).getNumMonths();
default:
return null;
}
}
}
如果有帮助,请在此处输入哈希集代码
public class SubList {
HashSet <Sub> subs = new HashSet<>();
private String listOfSubsFileName = "subs.ser";
public SubList() {
this.readSubListFile();
if (subs.isEmpty() || subs == null) {
this.createTestSubList();
this.writeSubListFile();
this.readSubListFile();
}
this.printSubList();
}
public HashSet<Sub> getSubList() {
return subs;
}
HashSet
是一个集合,而不是列表(即HashSet实现Set接口)。 HashSet
没有固有的顺序,因此,您不应将集合视为具有行或列。
Javadoc:https://docs.oracle.com/javase/10/docs/api/java/util/HashSet.html
代替使用HashSet,您应该考虑查看实现List接口的其他java.util.*
类。列表是可迭代的并且具有顺序,因此您可以通过它们的索引来引用它们。
Javadoc:https://docs.oracle.com/javase/10/docs/api/java/util/List.html
查看:所有已知的实现类
很难弄清楚您要做什么,但是我认为您可能会将HashSet
与HashTable
混淆了。前者仅存储您放入其中的任何内容,并丢弃重复项;后者根据键存储对象,其中键是您要检索它时对象的索引或名称。
因此您可以根据员工编号存储员工记录:
HashTable<int, Employee> employeeList = new HashTable<>();
您可以将员工记录存储在HashSet中,但是您不能根据员工编号来检索它们,只能对其进行遍历。 HashSet没有排序,因此您不能通过索引获取,它也没有键,因此您不能通过键获取(因为HashTable允许)。
希望有所帮助。
与ArrayList和LikedList不同,HashSet没有get方法。如果要迭代HashSet中的值,请使用迭代器。 get()不适用于HashSet。