如何从数组列表中删除某些单词? -java

时间:2015-07-21 23:11:10

标签: java arraylist

import java.util.ArrayList;


public class U3A4_CDCollection extends javax.swing.JFrame {
ArrayList <String> strArray = new ArrayList();

/**
 * Creates new form U3A4_CDCollection
 */
public U3A4_CDCollection() {
    initComponents();
}


@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    lblTitle = new javax.swing.JLabel();
    lblName = new javax.swing.JLabel();
    txtInputName = new javax.swing.JTextField();
    togbtnInitialize = new javax.swing.JToggleButton();
    togbtnRemove = new javax.swing.JToggleButton();
    togbtnAdd = new javax.swing.JToggleButton();
    togbtnDisplay = new javax.swing.JToggleButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    txtAreaOutput = new javax.swing.JTextArea();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    lblTitle.setFont(new java.awt.Font("Sylfaen", 1, 36)); // NOI18N
    lblTitle.setText("CD Collection");

    lblName.setFont(new java.awt.Font("Sylfaen", 0, 14)); // NOI18N
    lblName.setText("Title - Artist");

    txtInputName.setFont(new java.awt.Font("Sylfaen", 0, 14)); // NOI18N

    togbtnInitialize.setFont(new java.awt.Font("Sylfaen", 0, 14)); // NOI18N
    togbtnInitialize.setText("Initialize");
    togbtnInitialize.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            togbtnInitializeActionPerformed(evt);
        }
    });

    togbtnRemove.setFont(new java.awt.Font("Sylfaen", 0, 14)); // NOI18N
    togbtnRemove.setText("Remove");
    togbtnRemove.setEnabled(false);
    togbtnRemove.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            togbtnRemoveActionPerformed(evt);
        }
    });

    togbtnAdd.setFont(new java.awt.Font("Sylfaen", 0, 14)); // NOI18N
    togbtnAdd.setText("Add");
    togbtnAdd.setEnabled(false);
    togbtnAdd.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            togbtnAddActionPerformed(evt);
        }
    });

    togbtnDisplay.setFont(new java.awt.Font("Sylfaen", 0, 14)); // NOI18N
    togbtnDisplay.setText("Display");
    togbtnDisplay.setEnabled(false);

    txtAreaOutput.setEditable(false);
    txtAreaOutput.setColumns(20);
    txtAreaOutput.setLineWrap(true);
    txtAreaOutput.setRows(5);
    txtAreaOutput.setWrapStyleWord(true);
    jScrollPane1.setViewportView(txtAreaOutput);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(34, 34, 34)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(jScrollPane1)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(lblName)
                        .addComponent(togbtnDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(24, 24, 24)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(togbtnInitialize)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(togbtnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(togbtnRemove))
                        .addComponent(lblTitle)
                        .addComponent(txtInputName, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE))))
            .addContainerGap(43, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(lblTitle)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(txtInputName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(lblName))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(togbtnDisplay)
                .addComponent(togbtnInitialize)
                .addComponent(togbtnRemove)
                .addComponent(togbtnAdd))
            .addGap(29, 29, 29)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(34, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void togbtnAddActionPerformed(java.awt.event.ActionEvent evt) {                                          
    strArray.add(this.txtInputName.getText());
    System.out.println(strArray);
    this.txtAreaOutput.setText(txtAreaOutput.getText() + "\n" + strArray.get(strArray.size()));

}                                         

private void togbtnInitializeActionPerformed(java.awt.event.ActionEvent evt) {                                                 
    togbtnAdd.setEnabled(true);
    togbtnRemove.setEnabled(true);
    togbtnDisplay.setEnabled(true);

    String[] strArray = {"Calvin Harris - Overdrive(Part 2)", "DVBBS & Borgeous - TSUNAMI", "Martin Garrix - Tremor", "Martin Garrix - Animals", "Firebeatz - Max Ammo"};
    int intArrayLength = strArray.length;
    for (int i = 0; i < intArrayLength; i++){
        this.txtAreaOutput.setText(txtAreaOutput.getText() + "\n" + strArray[i]);

    }


    togbtnInitialize.setEnabled(false);

}                                                

private void togbtnRemoveActionPerformed(java.awt.event.ActionEvent evt) {                                             
    String strRemove = this.txtInputName.getText();
    System.out.print(strArray);
    for (int i = 0; i < strArray.size(); i++){
        if (strArray.get(i).equals(strRemove)){
            strArray.remove(strRemove);
        }
    }
    System.out.print(strArray);
}                                            

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(U3A4_CDCollection.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(U3A4_CDCollection.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(U3A4_CDCollection.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(U3A4_CDCollection.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new U3A4_CDCollection().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblName;
private javax.swing.JLabel lblTitle;
private javax.swing.JToggleButton togbtnAdd;
private javax.swing.JToggleButton togbtnDisplay;
private javax.swing.JToggleButton togbtnInitialize;
private javax.swing.JToggleButton togbtnRemove;
private javax.swing.JTextArea txtAreaOutput;
private javax.swing.JTextField txtInputName;
// End of variables declaration                   

}

我试图通过这样做从strArray中删除一个字符串,但是当我运行它时,它似乎没有做任何事情。任何帮助将不胜感激!提前致谢。

编辑:包含其余代码

2 个答案:

答案 0 :(得分:1)

通过避免

,您可以稍微提高代码的可读性(和性能)
area.setText(area.getText()+newText);

相反,你可以简单地使用

area.append(newText);
顺便说一句,您应该使用JButton代替JToggleButton

现在第一个问题是你togbtnInitializeActionPerformed内部正在创建本地数组

String[] strArray = {"Calvin Harris..."};

与你的领域无关

ArrayList<String> strArray = new ArrayList();

所以此列表保持空白。

也许考虑更像

的东西
    strArray = new ArrayList<>(Arrays.asList(
                    "Calvin Harris - Overdrive(Part 2)",
                    "DVBBS & Borgeous - TSUNAMI", 
                    "Martin Garrix - Tremor",
                    "Martin Garrix - Animals", 
                    "Firebeatz - Max Ammo"));
    for (String value : strArray) {
        this.txtAreaOutput.append(value + "\n");
    }

其他问题是togbtnAddActionPerformed你正在使用

strArray.get(strArray.size())

表示对于大小为n的列表,您尝试使用n对元素编制索引,但由于元素是从0索引的,n - 元素将具有索引n-1因为

{0, 1, 2, ..., n-2, n-1} => n-elements

所以如果你想获得最后一个元素

strArray.get(strArray.size()-1)

您的togbtnInitializeActionPerformed方法也有不必要的循环。简单的电话

strArray.remove(strRemove);

应该处理strRemove列表中strArray的删除txtAreaOutput.setText(""); for (String value : strArray) { this.txtAreaOutput.append(value + "\n"); } 值。

另一件事是这个方法缺少代码,它会将列表中的元素重绘为textarea,如

secpwgen

答案 1 :(得分:0)

有一个remove方法接受一个对象作为参数,如果它在列表中,则将其从列表中删除。

strArray.remove(strRemove);

如果删除了Object(意味着在调用方法时它就在那里),则该方法返回true,否则返回false,所以如果你想删除String的所有实例,你可以这样做:

while(strArray.remove(strRemove)){}

将删除列表中String的所有实例,直到不再存在。