2012-03-12 103 views
0

我需要能够在链接列表中查找和替换用户信息。我一直在阅读几个教程和例子,但它似乎没有工作。用于链接列表的设置方法不起作用。所以我想知道我是否实施了错误或什么。任何帮助都会很棒。也仅仅FYI我的链表是从一个文件加载的,基本上它的用户信息与每个元素在不同的行上。查找并替换链接列表中的节点

 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
int index = account.indexOf(hobby); 
account.set(index, "New String"); 

这里的问题是对的indexOf()将返回-1,因为它搜索字符串值与帐户值的列表中。

您不能在列表中按其元素的字段进行搜索。您必须手动搜索该帐户,然后设置业余爱好字段:

for(Account acc : account){ 
    if(acc.getHobby().equals(hobby)){ 
     acc.setHobby("New String"); 
    } 
} 
+0

谢谢,但可以说我先找到了用户名。我将如何迭代到每个下一个节点,然后改变它们?主要是因为用户名永远不会改变。我只想要选择改变一切。 – 2012-03-12 22:41:56

+0

基本上,当您创建一个List时,您可以期望indexOf方法仅为先前放入的对象返回有意义的值。但是您需要在列表中搜索某个字段中具有特定值的元素。列表不能为你做这个。您必须通过for循环手动搜索并检查每个对象内部。然后,您可以根据自己的意愿进行搜索,并根据需要进行修改。 – 2012-03-12 22:46:03

+0

甜蜜的谢谢生病试图弄清楚 – 2012-03-12 22:50:59