查找和替换链接列表中的节点

时间:2012-03-12 22:25:04

标签: java linked-list

我需要能够在链接列表中查找和替换用户信息。我一直在阅读几个教程和示例,但似乎没有用。用于链接列表的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
    {

    }

}

1 个答案:

答案 0 :(得分:1)

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");
    }
}