1

我按照这个关于 JPasswordField 的 Oracles 教程创建了一个简单的演示应用程序:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.SwingUtilities;

public class JPasswordFieldDemo {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    JPasswordField passwordField = new JPasswordField(20);
    JButton button = new JButton("Login");

    public JPasswordFieldDemo() {
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                char[] input = passwordField.getPassword();
                if (performCheck(input)) {
                    JOptionPane.showMessageDialog(null, "Correct password");
                } else {
                    JOptionPane.showMessageDialog(null, "Incorrect password");
                }
            }
        });
        passwordField.setEchoChar('*');
        panel.add(passwordField);
        panel.add(button);

        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private boolean performCheck(char[] input) {
        boolean isCorrect = false;
        char[] correctPass = { '1', '2', '3' };

        if (input.length != correctPass.length) {
            isCorrect = false;
        }
        if (Arrays.equals(input, correctPass)) {
            isCorrect = true;
        }
        Arrays.fill(correctPass, '0');

        return isCorrect;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JPasswordFieldDemo();
            }
        });
    }
}

现在,让我感到困惑的部分是performCheck方法。我的问题是:

有什么好的理由我应该比较两个 char 数组的长度(就像他们在教程中所做的那样)?

或者我的方法也可以是这样的:

private boolean performCheck(char[] input) {
        boolean isCorrect = false;
        char[] correctPass = { '1', '2', '3' };

        if (Arrays.equals(input, correctPass)) {
            isCorrect = true;
        }
        Arrays.fill(correctPass, '0');

        return isCorrect;
    }

问候,并提前感谢。

4

2 回答 2

2

您的示例不反映教程中显示的谓词,它首先检查长度,然后在长度匹配时检查内容。长度不等的数组永远不可能相等。

if (input.length != correctPassword.length) {
    isCorrect = false;
} else {
    isCorrect = Arrays.equals (input, correctPassword);
}
于 2013-05-12T18:16:19.303 回答
1

有什么好的理由我应该比较两个 char 数组的长度(就像他们在教程中所做的那样)?

Arrays.equals(..)如果您查看源代码,我认为在比较字符之前也不需要这样做:

public static boolean equals(char[] a, char[] a2) {
    if (a==a2)
        return true;
    if (a==null || a2==null)
        return false;

    int length = a.length;
    if (a2.length != length)
        return false;

    for (int i=0; i<length; i++)
        if (a[i] != a2[i])
            return false;

    return true;
}
于 2013-05-12T17:36:19.340 回答