我需要能够在链表中查找和替换用户信息。我已经阅读了一些教程和示例,但似乎不起作用。用于链表的set方法不起作用。所以我想知道我是不是实施错了。任何帮助都会很棒。此外,仅供参考,我的链表是从一个文件加载的,基本上它只是用户信息,每个元素都在不同的行上。
即
int index = account.indexOf(hobby);
account.set(index, "New String");
代码:
private void jButtonP1ActionPerformed(java.awt.event.ActionEvent evt) {
LinkedList<Account> account = new LinkedList<Account>();
//user information
String username = jTextFieldP3.getText();
String password = jPasswordFieldP1.getText();
String email = jTextFieldP4.getText();
String name = jTextFieldP1.getText();
String breed = (String) jComboBoxP4.getSelectedItem();
String gender = (String) jComboBoxP3.getSelectedItem();
String age = (String) jComboBoxP1.getSelectedItem();
String state = (String) jComboBoxP2.getSelectedItem();
String hobby = jTextFieldP2.getText();
//combo boxes
String passchange = (String) jComboBoxP13.getSelectedItem();
String emailchange = (String) jComboBoxP14.getSelectedItem();
String namechange = (String) jComboBoxP6.getSelectedItem();
String breedchange = (String) jComboBoxP7.getSelectedItem();
String genderchange = (String) jComboBoxP8.getSelectedItem();
String agechange = (String) jComboBoxP9.getSelectedItem();
String statechange = (String) jComboBoxP10.getSelectedItem();
String hobbychange = (String) jComboBoxP11.getSelectedItem();
String accountcancel = (String) jComboBoxP5.getSelectedItem();
Account a = new Account(username, password, email, name, breed, gender, age, state, hobby);
account.add(a);
if(username.equals("") || password.equals("") || email.equals("")) // If password and username is empty > Do this >>>
{
jButtonP1.setEnabled(false);
jTextFieldP3.setText("");
jPasswordFieldP1.setText("");
jTextFieldP4.setText("");
jButtonP1.setEnabled(true);
this.setVisible(true);
}
else if(a.onList(username) || a.onList(password) || a.onList(email))
{
int index = account.indexOf(hobby);
account.set(index, "New String");
}
else
{
}
}
int index = account.indexOf(hobby);
account.set(index, "New String");
这里的问题是indexOf()将返回-1,因为它在具有Account值的列表中搜索String值。
不能按列表中元素的字段进行搜索。您必须手动搜索该帐户,然后设置爱好字段:
for(Account acc : account){
if(acc.getHobby().equals(hobby)){
acc.setHobby("New String");
}
}