gpt4 book ai didi

java - 如何从 Array 切换到 ArrayList?

转载 作者:行者123 更新时间:2023-12-01 13:42:22 25 4
gpt4 key购买 nike

我现在已将所有数据保存到数组中。我如何将其切换为保存在对象的 ArrayList 中?我编写了一个基本的学生对象类,但需要帮助将其切换为保存在数组列表中。非常感谢所有帮助。 arraylist 在第 28 行创建,数据在第 300 行设置。问题是如何修改代码以存储在 ArrayList 中

public class IAdvise extends JFrame {

DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String[] columnNames = {"ID", "Name", "Major", "GPA", "Campus", "Home Address", "Phone Number", "Email", "Current CST courses", "Past CST course", "Fusture CST courses", "Notes"};
Object[][] data = new Object[60][12];
ArrayList<Student> al = new ArrayList<Student>();

JTable table = new JTable(data, columnNames) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
JFrame frame, frame1;
JPanel buttonPanel, buttonPanel2, tablePanel, addPanel, editPanel;
JLabel labelID, labelName, labelMajor, labelGPA, labelCampus, labelAddress, labelPhone, labelEmail,labelCurrent, labelPast, labelFuture, labelNotes;
JTextField txtID, txtName, txtMajor, txtGPA, txtCampus, txtAddress, txtPhone, txtEmail, txtCurrent, txtPast, txtFuture, txtNotes;
JButton btnAdd, btnEdit, btnDelete, btnSort, btnSave, btnAddInput, btnCancel;
int keyCode, rowIndex, rowNumber, noOfStudents;
IAdvise.ButtonHandler bh = new IAdvise.ButtonHandler();


public IAdvise() {
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new IAdvise.RowListener());
table.getColumnModel().getColumn(1).setPreferredWidth(150);
table.getColumnModel().getColumn(2).setPreferredWidth(150);
table.getColumnModel().getColumn(3).setPreferredWidth(50);
table.getColumnModel().getColumn(4).setPreferredWidth(200);
table.getColumnModel().getColumn(5).setPreferredWidth(250);
table.getColumnModel().getColumn(6).setPreferredWidth(150);
table.getColumnModel().getColumn(7).setPreferredWidth(150);
table.getColumnModel().getColumn(8).setPreferredWidth(150);
table.getColumnModel().getColumn(9).setPreferredWidth(150);
table.getColumnModel().getColumn(10).setPreferredWidth(150);
table.getColumnModel().getColumn(11).setPreferredWidth(150);

table.getTableHeader().setResizingAllowed(false);
table.getTableHeader().setReorderingAllowed(false);
JScrollPane scrollPane = new JScrollPane(table);

btnAdd = new JButton("Add Student");
btnAdd.addActionListener(bh);
btnEdit = new JButton("EDIT");
btnEdit.addActionListener(bh);
btnEdit.setEnabled(false);
btnDelete = new JButton("DELETE");
btnDelete.addActionListener(bh);
btnDelete.setEnabled(false);
btnSort = new JButton("Update");
btnSort.addActionListener(bh);
btnSave = new JButton("SAVE");
btnSave.addActionListener(bh);
btnSave.setActionCommand("Save");


btnAddInput = new JButton("Add Student");
btnAddInput.addActionListener(bh);
btnAddInput.setActionCommand("AddInput");
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(bh);

labelID = new JLabel("ID");
labelName = new JLabel("NAME");
labelMajor = new JLabel("Major");
labelGPA = new JLabel("GPA");
labelCampus = new JLabel("Campus");
labelAddress = new JLabel("Address");
labelPhone = new JLabel("Phone Number");
labelEmail = new JLabel("Email");
labelCurrent = new JLabel("Current CST courses");
labelPast = new JLabel("Past CST courses");
labelFuture = new JLabel("Future CST courses");
labelNotes = new JLabel("Notes");
txtID = new JTextField(20);
txtName = new JTextField(20);
txtMajor = new JTextField(20);
txtGPA = new JTextField(20);
txtCampus = new JTextField(20);
txtAddress = new JTextField(20);
txtPhone = new JTextField(20);
txtEmail = new JTextField(20);
txtCurrent = new JTextField(20);
txtPast = new JTextField(20);
txtFuture = new JTextField(20);
txtNotes = new JTextField(20);


txtID.setDocument(new IAdvise.JTextFieldLimit(8));

txtID.addKeyListener(keyListener);

tablePanel = new JPanel();
tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS));
tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 2, 0, 10));
tablePanel.add(table.getTableHeader());
tablePanel.add(table);
JScrollPane jScrollPane = new JScrollPane(tablePanel);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scrollPane.setBounds(50, 30, 300, 50);
JPanel contentPane = new JPanel(null);
contentPane.setPreferredSize(new Dimension(500, 400));
contentPane.add(scrollPane);

buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();

c.gridx = 0;
c.gridy = 0;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnAdd, c);
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnEdit, c);
c.gridx = 0;
c.gridy = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnDelete, c);
c.gridx = 0;
c.gridy = 3;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSort, c);
c.gridx = 0;
c.gridy = 4;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSave, c);

frame = new JFrame("Tutoring Database");
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(tablePanel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.EAST);
frame.pack();

addPanel = new JPanel();
addPanel.setLayout(new GridBagLayout());

c.insets = new Insets(1, 0, 1, 1);
c.gridx = 0;
c.gridy = 0;
addPanel.add(labelID, c);
c.gridy = 1;
addPanel.add(labelName, c);
c.gridy = 2;
addPanel.add(labelMajor, c);
c.gridy = 3;
addPanel.add(labelGPA, c);
c.gridy = 4;
addPanel.add(labelCampus, c);
c.gridy = 5;
addPanel.add(labelAddress, c);
c.gridy = 6;
addPanel.add(labelPhone, c);
c.gridy = 7;
addPanel.add(labelEmail, c);
c.gridy = 8;
addPanel.add(labelCurrent, c);
c.gridy = 9;
addPanel.add(labelPast, c);
c.gridy = 10;
addPanel.add(labelFuture, c);
c.gridy = 11;
addPanel.add(labelNotes, c);
// text fields
c.gridx = 1;
c.gridy = 0;
c.ipady = 1;
addPanel.add(txtID, c);
c.gridy = 1;
c.ipady = 1;
addPanel.add(txtName, c);
c.gridy = 2;
c.ipady = 1;
addPanel.add(txtMajor, c);
c.gridy = 3;
c.ipady = 1;
addPanel.add(txtGPA, c);
c.gridy = 4;
c.ipady = 1;
addPanel.add(txtCampus, c);
c.gridy = 5;
c.ipady = 1;
addPanel.add(txtAddress, c);
c.gridy = 6;
c.ipady = 1;
addPanel.add(txtPhone, c);
c.gridy = 7;
c.ipady = 1;
addPanel.add(txtEmail, c);
c.gridy = 8;
c.ipady = 1;
addPanel.add(txtCurrent, c);
c.gridy = 9;
c.ipady = 1;
addPanel.add(txtPast, c);
c.gridy = 10;
c.ipady = 1;
addPanel.add(txtFuture, c);
c.gridy = 11;
c.ipady = 1;
addPanel.add(txtNotes, c);

buttonPanel2 = new JPanel();
buttonPanel2.setLayout(new GridLayout(1, 1));
buttonPanel2.add(btnAddInput);
buttonPanel2.add(btnCancel);

frame1 = new JFrame("Student Database");
frame1.setVisible(false);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(HIDE_ON_CLOSE);
frame1.add(addPanel, BorderLayout.CENTER);
frame1.add(buttonPanel2, BorderLayout.PAGE_END);
frame1.pack();
}// end

KeyListener keyListener = new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}

@Override
public void keyPressed(KeyEvent e) {
keyCode = e.getKeyCode();

if (!(keyCode >= 48 && keyCode <= 57) && !(keyCode >= 96 && keyCode <= 105)
&& !(keyCode >= 37 && keyCode <= 40) && !(keyCode == 127 || keyCode == 8)) {
txtID.setEditable(false);
}
}

@Override
public void keyReleased(KeyEvent e) {
txtID.setEditable(true);
}
};

class RowListener implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
}

class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {

if (e.getActionCommand().equals("Add Student")) {
txtID.setText("");
txtName.setText("");
txtMajor.setText("");
txtGPA.setText("");
txtCampus.setText("");
txtAddress.setText("");
txtPhone.setText("");
txtEmail.setText("");
txtCurrent.setText("");
txtPast.setText("");
txtFuture.setText("");
txtNotes.setText("");
Student student = new Student(txtID.getText(), txtName.getName(), txtMajor.getText(), txtGPA.getText(), txtCampus.getText(), txtAddress.getText(), txtPhone.getText(),txtEmail.getText(), txtCurrent.getText(), txtPast.getText(), txtFuture.getText(), txtNotes.getText());
al.add(student);

frame1.setTitle("Add Student data"); // title bar name for add
frame1.setVisible(true);

} else if (e.getActionCommand().equals("EDIT")) {
txtID.setText(data[rowIndex][0] + "");
txtName.setText(data[rowIndex][1] + "");
txtMajor.setText(data[rowIndex][2] + "");
txtGPA.setText(data[rowIndex][3] + "");
txtCampus.setText(data[rowIndex][4] + "");
txtAddress.setText(data[rowIndex][5] + "");
txtPhone.setText(data[rowIndex][6] + "");
txtEmail.setText(data[rowIndex][7] + "");
txtCurrent.setText(data[rowIndex][8] + "");
txtPast.setText(data[rowIndex][9] + "");
txtFuture.setText(data[rowIndex][10] + "");
txtNotes.setText(data[rowIndex][11] + "");
txtID.setEditable(false);
frame1.setTitle("Enter Student data");
btnAddInput.setActionCommand("Edit2");
btnAddInput.setText("ACCEPT");

frame1.setVisible(true);
} else if (e.getActionCommand().equals("DELETE")) {
int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
JOptionPane.YES_NO_OPTION);

if (confirm == 0) {
rowIndex = table.getSelectedRow();
rowNumber = 0;

noOfStudents--;
for (int i = 0; i <= 10; i++) {
if (rowIndex != i && i <= noOfStudents) {
data[rowNumber][0] = data[i][0];
data[rowNumber][1] = data[i][1];
data[rowNumber][2] = data[i][2];
data[rowNumber][3] = data[i][3];
data[rowNumber][4] = data[i][4];
data[rowNumber][5] = data[i][5];
data[rowNumber][6] = data[i][6];
data[rowNumber][7] = data[i][7];
data[rowNumber][8] = data[i][8];
data[rowNumber][9] = data[i][9];
data[rowNumber][10] = data[i][10];
data[rowNumber][11] = data[i][11];


rowNumber++;
} else if (rowIndex != i && i > noOfStudents) {
data[rowNumber][0] = "";
data[rowNumber][1] = "";
data[rowNumber][2] = "";
data[rowNumber][3] = "";
data[rowNumber][4] = "";
data[rowNumber][5] = "";
data[rowNumber][6] = "";
data[rowNumber][7] = "";
data[rowNumber][8] = "";
data[rowNumber][9] = "";
data[rowNumber][10] = "";
data[rowNumber][11] = "";

rowNumber++;
}
}
if (noOfStudents == 1000) {
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (noOfStudents == 0) {
btnDelete.setEnabled(false);
btnEdit.setEnabled(false);
} else {
btnDelete.setEnabled(true);
btnEdit.setEnabled(true);
}

rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}

table.updateUI();

}
} else if (e.getActionCommand().equals("AddInput")) {

if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtMajor.getText().isEmpty()// /
|| txtGPA.getText().isEmpty() || txtCampus.getText().isEmpty()|| txtEmail.getText().isEmpty()
|| txtCurrent.getText().isEmpty()|| txtPast.getText().isEmpty()|| txtFuture.getText().isEmpty()
|| txtNotes.getText().isEmpty() || txtPhone.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "PLEASE FILL IN THE BLANKS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
}
else {
int dup = 0;
for (int i = 0; i < 8; i++) {
if (txtID.getText().equals(data[i][0])) {
JOptionPane.showMessageDialog(null, "ID NUMBER ALREADY EXISTS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
dup++;
}
}
if (dup == 0) {
rowIndex = table.getSelectedRow();
data[noOfStudents][0] = txtID.getText();
data[noOfStudents][1] = txtName.getText();
data[noOfStudents][2] = txtMajor.getText();
data[noOfStudents][3] = txtGPA.getText();
data[noOfStudents][4] = txtCampus.getText();
data[noOfStudents][5] = txtAddress.getText();
data[noOfStudents][6] = txtPhone.getText();
data[noOfStudents][7] = txtEmail.getText();
data[noOfStudents][8] = txtCurrent.getText();
data[noOfStudents][9] = txtPast.getText();
data[noOfStudents][10] = txtFuture.getText();
data[noOfStudents][11] = txtNotes.getText();



table.updateUI();
frame1.dispose();
noOfStudents++;
if (noOfStudents == 50){
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (data[rowIndex][0] == null) {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
table.updateUI();
}else if(e.getActionCommand().equals("Save")){
try {
PrintWriter out = new PrintWriter("Tutor.txt");
for(int i = 0; i < 25; i++)
{
for(int j = 0; j < 10; j++)
{
out.print(data[i][j]);
out.print(", ");
if(j == 10){
out.println();
}
} out.flush();

}} catch (FileNotFoundException ex) {
}
} else if (e.getActionCommand().equals("Update")) {

}
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtMajor.getText().isEmpty()// /
|| txtGPA.getText().isEmpty() || txtCampus.getText().isEmpty()|| txtEmail.getText().isEmpty()
|| txtCurrent.getText().isEmpty()|| txtPast.getText().isEmpty()|| txtFuture.getText().isEmpty()
|| txtNotes.getText().isEmpty()) {
} else {
data[rowIndex][0] = txtID.getText();
data[rowIndex][1] = txtName.getText();
data[rowIndex][2] = txtMajor.getText();
data[rowIndex][3] = txtGPA.getText();
data[rowIndex][4] = txtCampus.getText();
data[rowIndex][5] = txtAddress.getText();
data[rowIndex][6] = txtPhone.getText();
data[rowIndex][7] = txtEmail.getText();
data[rowIndex][8] = txtEmail.getText();
data[rowIndex][9] = txtEmail.getText();
data[rowIndex][10] = txtEmail.getText();
data[rowIndex][11] = txtEmail.getText();


frame1.dispose();
}
table.updateUI();

}
}

class JTextFieldLimit extends PlainDocument {
private int limit;

JTextFieldLimit(int limit) {
super();
this.limit = limit;
}

JTextFieldLimit(int limit, boolean upper) {
super();
this.limit = limit;
}

@Override
public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) {
return;
}

if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
public static void main(String[] args) {
new IAdvise();
}
}

学生类(class):

public class Student implements java.io.Serialize{
private final String id;
private final String name;
private final String major;
private final String gpa;
private final String campus;
private final String address;
private final String number;
private final String email;
private final String current;
private final String past;
private final String future;


public Student(String id, String name, String major,String gpa, String campus, String address,String number, String email, String current, String past, String future, String notes) {
this.id = id;
this.name = name;
this.major = major;
this.gpa = gpa;
this.campus = campus;
this.address = address;
this.number = number;
this.email = email;
this.current = current;
this.past = past;
this.future = future;
}
}

最佳答案

将使用数组的代码更改为使用 ArrayList 的代码:

  1. 而不是 a[i] ,当它不在作业的左侧时,请使用 a.get(i)

  2. 而不是 a.length ,使用a.size()

  3. 而不是设置 a[i] = expression :如果i已知在范围内 (0 <= i <= a.length-1 ),请使用 a.set(i, expression) 。如果i == a.length ,您不能使用a[i] = expression使用数组,但您可以使用 ArrayList 来完成,将大小增加 1: a.add(expression) 。如果i > a.length ,以便您想要在 ArrayList 中添加一个新元素留下一个间隙,然后是这样的:

    while (a.size() < i)
    a.add (null);
    // at this point a.size == i
    a.add (expression);
    // now a.size == i+1

这应该涵盖数组上的所有基本操作。 Arrays 中定义了一些实用程序操作。 ArrayList 中没有等效操作,例如binarySearch .

关于java - 如何从 Array 切换到 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20623209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com