| | |
Confuzzled in sorting arraylist...
Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: May 2009
Posts: 23
Reputation:
Solved Threads: 0
hey guys, im very new to java so bare with me...
i cant seem to bubble sort my arraylist...
The data needs to be displayed unsorted in a jlist, then when user clicks process the list is sorted according to student id.
If anyone could guide me through it would be great because ive been stuck on it for days....
i dont know how much code you need but im going to post all of it & if you need anymore details please let me know.
Thanks to anyone in advance...
i cant seem to bubble sort my arraylist...
The data needs to be displayed unsorted in a jlist, then when user clicks process the list is sorted according to student id.
If anyone could guide me through it would be great because ive been stuck on it for days....
i dont know how much code you need but im going to post all of it & if you need anymore details please let me know.
Thanks to anyone in advance...
Java Syntax (Toggle Plain Text)
package assignment2009; import java.awt.event.MouseEvent; import javax.swing.*; import java.awt.event.MouseListener; import java.util.*; public class MainApplication extends javax.swing.JFrame implements MouseListener { public MainApplication() { initComponents(); tfJList.addMouseListener(this); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { top1Panel = new javax.swing.JPanel(); clearTFButton = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tfJList = new javax.swing.JList(); top2Panel = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); newMFile = new javax.swing.JList(); infoBarButton = new javax.swing.JLabel(); top3Panel = new javax.swing.JPanel(); clearMFButton = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); mfJList = new javax.swing.JList(); top4Panel = new javax.swing.JPanel(); jScrollPane4 = new javax.swing.JScrollPane(); errorLog = new javax.swing.JTextArea(); elLabel = new javax.swing.JLabel(); botton1Panel = new javax.swing.JPanel(); etButton = new javax.swing.JLabel(); blank = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); nameSur = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); iD = new javax.swing.JTextField(); previousButton = new javax.swing.JButton(); nextRecord = new javax.swing.JButton(); deleteButton = new javax.swing.JButton(); addButton = new javax.swing.JButton(); modifyButton = new javax.swing.JButton(); defaultRecordsButton = new javax.swing.JButton(); bottom2Panel = new javax.swing.JPanel(); soLabel = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); demoSpeedSlider = new javax.swing.JSlider(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); singleShotCB = new javax.swing.JCheckBox(); bottom3Panel = new javax.swing.JPanel(); dcLabel = new javax.swing.JLabel(); sDemoButton = new javax.swing.JButton(); pDemoButton = new javax.swing.JButton(); jToggleButton1 = new javax.swing.JToggleButton(); bottom4Panel = new javax.swing.JPanel(); jScrollPane5 = new javax.swing.JScrollPane(); helpTArea = new javax.swing.JTextArea(); helpButton = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new java.awt.GridLayout(2, 5)); top1Panel.setLayout(new java.awt.BorderLayout()); clearTFButton.setText("Clear Transaction File"); clearTFButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearTFButtonActionPerformed(evt); } }); top1Panel.add(clearTFButton, java.awt.BorderLayout.PAGE_END); tfJList.setBackground(new java.awt.Color(0, 204, 255)); tfJList.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2), "Transaction File", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Impact", 0, 13), new java.awt.Color(0, 0, 0))); // NOI18N tfJList.setModel(tranList); tfJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane1.setViewportView(tfJList); top1Panel.add(jScrollPane1, java.awt.BorderLayout.CENTER); getContentPane().add(top1Panel); top2Panel.setLayout(new java.awt.BorderLayout()); newMFile.setBackground(new java.awt.Color(255, 51, 51)); newMFile.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2), "New Master File", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Impact", 0, 13), new java.awt.Color(0, 0, 0))); // NOI18N newMFile.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane2.setViewportView(newMFile); top2Panel.add(jScrollPane2, java.awt.BorderLayout.CENTER); infoBarButton.setBackground(new java.awt.Color(102, 255, 51)); infoBarButton.setFont(new java.awt.Font("Tahoma", 2, 14)); infoBarButton.setForeground(new java.awt.Color(0, 51, 255)); infoBarButton.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); infoBarButton.setText("Info Bar"); infoBarButton.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 3, true)); top2Panel.add(infoBarButton, java.awt.BorderLayout.PAGE_END); getContentPane().add(top2Panel); top3Panel.setLayout(new java.awt.BorderLayout()); clearMFButton.setText("Clear Master File"); clearMFButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearMFButtonActionPerformed(evt); } }); top3Panel.add(clearMFButton, java.awt.BorderLayout.PAGE_END); mfJList.setBackground(new java.awt.Color(102, 255, 102)); mfJList.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2), "Master File", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Impact", 0, 13), new java.awt.Color(0, 0, 0))); // NOI18N mfJList.setModel(masterList); mfJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane3.setViewportView(mfJList); top3Panel.add(jScrollPane3, java.awt.BorderLayout.CENTER); getContentPane().add(top3Panel); top4Panel.setLayout(new java.awt.BorderLayout()); errorLog.setBackground(new java.awt.Color(0, 102, 204)); errorLog.setColumns(20); errorLog.setRows(5); jScrollPane4.setViewportView(errorLog); top4Panel.add(jScrollPane4, java.awt.BorderLayout.CENTER); elLabel.setFont(new java.awt.Font("Impact", 0, 13)); elLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); elLabel.setText("Error Log"); top4Panel.add(elLabel, java.awt.BorderLayout.PAGE_START); getContentPane().add(top4Panel); botton1Panel.setLayout(new java.awt.GridLayout(7, 2, 10, 10)); etButton.setFont(new java.awt.Font("Impact", 0, 13)); etButton.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); etButton.setText("Records"); botton1Panel.add(etButton); botton1Panel.add(blank); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel2.setText("Name / Surname:"); botton1Panel.add(jLabel2); nameSur.setHorizontalAlignment(javax.swing.JTextField.CENTER); nameSur.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nameSurActionPerformed(evt); } }); botton1Panel.add(nameSur); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel1.setText("ID Number:"); botton1Panel.add(jLabel1); iD.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { iDActionPerformed(evt); } }); botton1Panel.add(iD); previousButton.setText("< Previous Record"); previousButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); previousButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { previousButtonActionPerformed(evt); } }); botton1Panel.add(previousButton); nextRecord.setText("Next Record >"); nextRecord.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); nextRecord.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nextRecordActionPerformed(evt); } }); botton1Panel.add(nextRecord); deleteButton.setText("Delete Record"); deleteButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteButtonActionPerformed(evt); } }); botton1Panel.add(deleteButton); addButton.setText("Add Record"); addButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addButtonActionPerformed(evt); } }); botton1Panel.add(addButton); modifyButton.setText("Modify Record"); modifyButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { modifyButtonActionPerformed(evt); } }); botton1Panel.add(modifyButton); defaultRecordsButton.setText("Load Default Records"); defaultRecordsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { defaultRecordsButtonActionPerformed(evt); } }); botton1Panel.add(defaultRecordsButton); getContentPane().add(botton1Panel); bottom2Panel.setLayout(new java.awt.GridLayout(7, 1, 10, 10)); soLabel.setFont(new java.awt.Font("Impact", 0, 13)); soLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); soLabel.setText("Simulation Options"); bottom2Panel.add(soLabel); jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel4.setText("--- Automatic Simulation ---"); bottom2Panel.add(jLabel4); demoSpeedSlider.setMaximum(10); demoSpeedSlider.setMinimum(1); demoSpeedSlider.setMinorTickSpacing(1); demoSpeedSlider.setPaintLabels(true); demoSpeedSlider.setPaintTicks(true); demoSpeedSlider.setSnapToTicks(true); demoSpeedSlider.setValue(5); bottom2Panel.add(demoSpeedSlider); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("Slow Speed Fast"); jLabel3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); bottom2Panel.add(jLabel3); jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel5.setText("--- Manual Simulation ---"); bottom2Panel.add(jLabel5); singleShotCB.setText("Single Shot"); singleShotCB.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); bottom2Panel.add(singleShotCB); getContentPane().add(bottom2Panel); bottom3Panel.setLayout(new java.awt.GridLayout(7, 1, 10, 10)); dcLabel.setFont(new java.awt.Font("Impact", 0, 13)); dcLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); dcLabel.setText("Demonstration Controls"); bottom3Panel.add(dcLabel); sDemoButton.setText("Start Demonstration"); sDemoButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sDemoButtonActionPerformed(evt); } }); bottom3Panel.add(sDemoButton); pDemoButton.setText("Pause"); pDemoButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pDemoButtonActionPerformed(evt); } }); bottom3Panel.add(pDemoButton); jToggleButton1.setText("Next Step >"); bottom3Panel.add(jToggleButton1); getContentPane().add(bottom3Panel); bottom4Panel.setLayout(new java.awt.BorderLayout()); helpTArea.setBackground(new java.awt.Color(255, 255, 51)); helpTArea.setColumns(20); helpTArea.setEditable(false); helpTArea.setFont(new java.awt.Font("Monospaced", 0, 12)); helpTArea.setLineWrap(true); helpTArea.setRows(5); helpTArea.setText("Step 1\nAdd records to transaction file.\n\nStep 2\nSelect speed of demonstration or select single shot to process data in an instant.\n\nStep 3\nSelect Start Demonstation!"); helpTArea.setWrapStyleWord(true); jScrollPane5.setViewportView(helpTArea); bottom4Panel.add(jScrollPane5, java.awt.BorderLayout.CENTER); helpButton.setFont(new java.awt.Font("Impact", 0, 13)); helpButton.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); helpButton.setText("Help "); bottom4Panel.add(helpButton, java.awt.BorderLayout.PAGE_START); getContentPane().add(bottom4Panel); pack(); }// </editor-fold> private void clearTFButtonActionPerformed(java.awt.event.ActionEvent evt) { tranList.clear(); infoBarButton.setText("Transaction File Cleared"); } private void addButtonActionPerformed(java.awt.event.ActionEvent evt) { addRecord(); } private void modifyButtonActionPerformed(java.awt.event.ActionEvent evt) { modify(); } private void defaultRecordsButtonActionPerformed(java.awt.event.ActionEvent evt) { addDefaultData(); } private void sDemoButtonActionPerformed(java.awt.event.ActionEvent evt) { sort.bubbleSort(studTranArray ); } private void pDemoButtonActionPerformed(java.awt.event.ActionEvent evt) { // PAUSE } private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) { delete(); } private void iDActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void clearMFButtonActionPerformed(java.awt.event.ActionEvent evt) { masterList.clear(); infoBarButton.setText("Master File Cleared"); } private void previousButtonActionPerformed(java.awt.event.ActionEvent evt) { previousRecord(); } private void nextRecordActionPerformed(java.awt.event.ActionEvent evt) { System.out.println(studTranArray.size()); nextRecord(); } private void nameSurActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainApplication().setVisible(true); } }); } //javax.swing.tfJList=newList; private DefaultListModel tranList = new DefaultListModel(); private DefaultListModel masterList = new DefaultListModel(); private DefaultListModel newMasterList = new DefaultListModel(); studentClass Nstudent = new studentClass(); //Default Transaction Array ArrayList studTranArray = new ArrayList(); Vector studentVector = new Vector(studTranArray); //Default Master File Array List defNameMasterList = new ArrayList(); //Creates List Objects for default //Default NewMaster File Array List defNameNewMasterList = new ArrayList(); int nOrecords=0; int index = 0; // Variables declaration - do not modify private javax.swing.JButton addButton; private javax.swing.JLabel blank; private javax.swing.JPanel bottom2Panel; private javax.swing.JPanel bottom3Panel; private javax.swing.JPanel bottom4Panel; private javax.swing.JPanel botton1Panel; private javax.swing.JButton clearMFButton; private javax.swing.JButton clearTFButton; private javax.swing.JLabel dcLabel; private javax.swing.JButton defaultRecordsButton; private javax.swing.JButton deleteButton; private javax.swing.JSlider demoSpeedSlider; private javax.swing.JLabel elLabel; private javax.swing.JTextArea errorLog; private javax.swing.JLabel etButton; private javax.swing.JLabel helpButton; private javax.swing.JTextArea helpTArea; private javax.swing.JTextField iD; private javax.swing.JLabel infoBarButton; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JToggleButton jToggleButton1; private javax.swing.JList mfJList; private javax.swing.JButton modifyButton; private javax.swing.JTextField nameSur; private javax.swing.JList newMFile; private javax.swing.JButton nextRecord; private javax.swing.JButton pDemoButton; private javax.swing.JButton previousButton; private javax.swing.JButton sDemoButton; private javax.swing.JCheckBox singleShotCB; private javax.swing.JLabel soLabel; private javax.swing.JList tfJList; private javax.swing.JPanel top1Panel; private javax.swing.JPanel top2Panel; private javax.swing.JPanel top3Panel; private javax.swing.JPanel top4Panel; // End of variables declaration //----------------------------------------------------------------- public void addRecord() { studTranArray.add(iD.getText()); studTranArray.add(nameSur.getText()); tranList.addElement(nameSur.getText()+" "+iD.getText()); clear(); infoBarButton.setText("Record Added To Transaction File!"); } //------------------------------------------------------------------ public void clear() { nameSur.setText(""); iD.setText(""); } //------------------------------------------------------------------ public void addDefaultData() { String [] defaultNames = {"Alvin Du","Ryan Gosden","Michelle Dowling","Toni Dowling"}; int [] defaultID = {153679,417950,234512,762903}; for (int i=0;i<4;i++) { Nstudent.setStudentName(defaultNames[i]); Nstudent.setStudentID(defaultID[i]); studTranArray.add(Nstudent); tranList.addElement(defaultNames[i]+" "+defaultID[i]); //adds arrays to JList } infoBarButton.setText("Default Records Loaded!"); } //------------------------------------------------------------------ public void delete() { System.out.println(index); if (index ==0 || index<0) { JOptionPane.showMessageDialog(null,"No More Records To Delete"); } else { tranList.remove(index); studTranArray.remove(index); } } //------------------------------------------------------------------ public void nextRecord() { int size =(studTranArray.size()); if (nOrecords<size) { iD.setText(studTranArray.get(nOrecords).toString()); nOrecords = nOrecords +1; } else { JOptionPane.showMessageDialog(null,"No More Records"); } } //------------------------------------------------------------------ public void previousRecord() { if(nOrecords>0) { nOrecords = nOrecords -1; iD.setText(studTranArray.get(nOrecords).toString()); } else { JOptionPane.showMessageDialog(null,"No More Records"); } } //------------------------------------------------------------------ public void modify() { tranList.remove(index); studTranArray.remove(index); studTranArray.add(iD.getText()); tranList.addElement(iD.getText()); } //------------------------------------------------------------------ //Sort Method!!!!!! public static void sort(ArrayList sortedList) { int count = 1; int size2 =(sortedList.size()); for (int i = 0; i < size2; i++) { System.out.print(sortedList.get(i) +" "); } if (count % 10 == 0) { System.out.println(); } count = count + 1; } static int bubbleSort(ArrayList <Integer> sortedList) { int count = 0; for (int outer = 0; outer < sortedList.size() - 1; outer++) { for (int inner = 0; inner < sortedList.size()-outer-1; inner++) { if (sortedList.get(inner) > sortedList.get(inner + 1)) { swapEm(sortedList, inner); count = count + 1; } } } return count; } static void swapEm(ArrayList<Integer>sortedList, int inner) { int temp = sortedList.get(inner); sortedList.set(inner, sortedList.get(inner + 1)); sortedList.set(inner + 1, temp); } //------------------------------------------------------------------ public void mouseClicked(MouseEvent e) { JList tranList = (JList)e.getSource(); if (e.getClickCount() == 1) { index = tranList.locationToIndex(e.getPoint()); iD.setText(studTranArray.get(index).toString()); nameSur.setText(studTranArray.get(index).toString()); infoBarButton.setText("Item Selected"); } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } }
Have look at this section from SCJP study guide
Learn to see in another's calamity the ills which you should avoid.
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
•
•
Join Date: May 2009
Posts: 23
Reputation:
Solved Threads: 0
I tried Collections.sort but i get this error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: assignment2009.studentClass cannot be cast to java.lang.Comparable
The arraylist i want to sort (studTranArray) contains a string and an integer.
While the example only shows a string being sorted...
is there a way to select the variable type you want for sorting and the String will follow?
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: assignment2009.studentClass cannot be cast to java.lang.Comparable
The arraylist i want to sort (studTranArray) contains a string and an integer.
While the example only shows a string being sorted...
is there a way to select the variable type you want for sorting and the String will follow?
Can you post your updated code please, so we see what you tried and where can be problem?
Learn to see in another's calamity the ills which you should avoid.
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
•
•
Join Date: Oct 2008
Posts: 103
Reputation:
Solved Threads: 14
Sorry about the code formatting. You have multiple things going on:
In "addDefaultData" you give the impression that "studTranArray" is a record.
Ok, records/struct don't really exist in Java so you can use a class to
try to achieve something similiar.
You do the following:
String [] defaultNames = {"Alvin Du","Ryan Gosden","Michelle Dowling","Toni Dowling"};
int [] defaultID = {153679,417950,234512,762903};
Nstudent.setStudentName(defaultNames[i]);
Nstudent.setStudentID(defaultID[i]);
studTranArray.add(Nstudent);
------------------------------------------------------------------------------
You declare "studTranArray" as follows:
ArrayList studTranArray = new ArrayList();
----------------------------------------------------
then in "addRecord", you do the following:
studTranArray.add(iD.getText());
studTranArray.add(nameSur.getText());
you are mixing what should probably be integer data (ID) with
String data (name). You need to keep your id's separate from
the names. Looks like you started to do this in "addDefaultData".
----------------------------------------------------
in "sDemoButtonActionPerformed" you call:
sort.bubbleSort(studTranArray );
but you declare "bubbleSort" as follows:
static int bubbleSort(ArrayList <Integer> sortedList)
------------------------------------------------------
Looks like you added "String" data to the array list and told
bubblesSort that you were going to pass it an "Integer" array list.
Even if you remove "<Integer>" from your bubbleSort declaration,
you can't compare String data with ">" or "<". You have to use
"compareTo" or "compareToIgnoreCase".
-------------------------------------------------------
I would recommend creating a separate class that separates the student data:
Then in the main application have something like the following:
In "addDefaultData" you give the impression that "studTranArray" is a record.
Ok, records/struct don't really exist in Java so you can use a class to
try to achieve something similiar.
You do the following:
String [] defaultNames = {"Alvin Du","Ryan Gosden","Michelle Dowling","Toni Dowling"};
int [] defaultID = {153679,417950,234512,762903};
Nstudent.setStudentName(defaultNames[i]);
Nstudent.setStudentID(defaultID[i]);
studTranArray.add(Nstudent);
------------------------------------------------------------------------------
You declare "studTranArray" as follows:
ArrayList studTranArray = new ArrayList();
----------------------------------------------------
then in "addRecord", you do the following:
studTranArray.add(iD.getText());
studTranArray.add(nameSur.getText());
you are mixing what should probably be integer data (ID) with
String data (name). You need to keep your id's separate from
the names. Looks like you started to do this in "addDefaultData".
----------------------------------------------------
in "sDemoButtonActionPerformed" you call:
sort.bubbleSort(studTranArray );
but you declare "bubbleSort" as follows:
static int bubbleSort(ArrayList <Integer> sortedList)
------------------------------------------------------
Looks like you added "String" data to the array list and told
bubblesSort that you were going to pass it an "Integer" array list.
Even if you remove "<Integer>" from your bubbleSort declaration,
you can't compare String data with ">" or "<". You have to use
"compareTo" or "compareToIgnoreCase".
-------------------------------------------------------
I would recommend creating a separate class that separates the student data:
Java Syntax (Toggle Plain Text)
package assignment2009; public class StudentClass { public StudentClass() { } protected String studentName; protected int studentID; public void setStudentName(String newStudentName) { this.studentName = newStudentName; } public String getStudentName() { return studentName; } public void setStudentID(int newStudentID) { this.studentID = newStudentID; } public int getStudentID() { return studentID; } }
Then in the main application have something like the following:
Java Syntax (Toggle Plain Text)
package assignment2009; import java.util.ArrayList; import java.util.Vector; import javax.swing.JOptionPane; public class MainApplication extends javax.swing.JFrame { //create array list of type StudentClass ArrayList<StudentClass> studTranArray = new ArrayList<StudentClass>(); //used to keep track of record number when pressing "previous" or "next" int recordNumber = 0; //used to keep track of how many array elements/students we have int recordCount = 0; //more code goes here //------------------------------------------------------------------ public void addDefaultData() { //may need to change some of the data around for testing //"order by name" and "order by id" results in students being in the exact same order String[] defaultNames = {"Alvin Du", "Ryan Gosden", "Michelle Dowling", "Toni Dowling"}; int[] defaultID = {153679, 417950, 234512, 762903}; //clear array of any previous data studTranArray.clear(); for (int i = 0; i < defaultNames.length; i++) { recordCount = recordCount + 1; //need to create new Nstudent for each loop //otherwise all data will = the last student entered StudentClass Nstudent = new StudentClass(); Nstudent.setStudentID(defaultID[i]); Nstudent.setStudentName(defaultNames[i]); studTranArray.add(Nstudent); } //displayData(studTranArray); //statusLbl.setText("Default Records Loaded!"); } //------------------------------------------------------------------ private void bubbleSort(ArrayList<StudentClass> sortedList, String sortBy) { //start with the first element in the array for (int outer = 0; outer < sortedList.size() - 1; outer++) { //compare "outer" element with rest of elements one by one //swap if necessary for (int inner = outer+1; inner < sortedList.size(); inner++) { //if sorting by id compare ids if (sortBy.equalsIgnoreCase("id")) { if (sortedList.get(outer).getStudentID() > sortedList.get(inner).getStudentID()) { statusLbl.setText("Swapping id:" + sortedList.get(inner).getStudentID() + " with " + sortedList.get(outer).getStudentID()); swapEm(sortedList, outer, inner); //displayData(sortedList); }//end if } else if(sortBy.equalsIgnoreCase("name")) { //use compareToIgnoreCase for String comparison int result = sortedList.get(outer).getStudentName().compareToIgnoreCase (sortedList.get(inner).getStudentName()); //if "outer name" is alphabetically after "inner name" swap them if (result > 0) { statusLbl.setText("Swapping id:" + sortedList.get(inner).getStudentNam() + " with " + sortedList.get(outer).getStudentName()); swapEm(sortedList, outer, inner); //displayData(sortedList); }//end if }//end else if }//end for }//end for } private void swapEm(ArrayList<StudentClass> sortedList, int outer, int inner) { StudentClass temp = sortedList.get(inner); sortedList.set(inner, sortedList.get(outer)); sortedList.set(outer, temp); } }//end MainApplication
Last edited by cgeier; Jul 26th, 2009 at 3:38 am.
•
•
•
•
I tried Collections.sort but i get this error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: assignment2009.studentClass cannot be cast to java.lang.Comparable
The arraylist i want to sort (studTranArray) contains a string and an integer.
While the example only shows a string being sorted...
is there a way to select the variable type you want for sorting and the String will follow?
Java Syntax (Toggle Plain Text)
// NULL checks and some other minor details omitted for brevity class Student implements Comparable<Student> { private String name; private int id; public Student(String name, int id) { this.id = id; this.name = name; } public String getName() { return this.name; } public int compareTo(Student student) { return this.id - student.id; } @Override public String toString() { return "{name:" + name + ",id:" + id + "}"; } } public class ProxyTest { public static void main(final String[] args) { List<Student> list = new ArrayList<Student>(); Student student = new Student("tom", 12); list.add(student); student = new Student("dick", 34); list.add(student); student = new Student("harry", 0); list.add(student); student = new Student("a sexy girl", -12); list.add(student); // Use the comparable nature of Student class when sorting i.e. sort by id Collections.sort(list); System.out.println(list); // Use a custom compare method which now sorts by name // Here we create an instance of anonymous class which implements the // Comarator interface. In case you need to re-use the same Comparator // at multiple places, create a proper class with the same code. Collections.sort(list, new Comparator<Student>() { public int compare(Student o1, Student o2) { return o1.getName().compareTo(o2.getName()); } }); System.out.println(list); } }
•
•
•
•
Originally Posted by output
[{name:a sexy girl,id:-12}, {name:harry,id:0}, {name:tom,id:12}, {name:dick,id:34}]
[{name:a sexy girl,id:-12}, {name:dick,id:34}, {name:harry,id:0}, {name:tom,id:12}]
I don't accept change; I don't deserve to live.
Jo Tujhe Jagaaye, Nindein Teri Udaaye Khwaab Hai Sachcha Wahi.
Nindon Mein Jo Aaye Jise To Bhul Jaaye Khawab Woh Sachcha Nahi.
Khwaab Ko Raag De, Nind Ko Aag De
Jo Tujhe Jagaaye, Nindein Teri Udaaye Khwaab Hai Sachcha Wahi.
Nindon Mein Jo Aaye Jise To Bhul Jaaye Khawab Woh Sachcha Nahi.
Khwaab Ko Raag De, Nind Ko Aag De
•
•
Join Date: May 2009
Posts: 23
Reputation:
Solved Threads: 0
It seems like i cant use Collections.sort because one of the main functionalities of this program is when the list gets sorted, the user has control over the speed of EACH record from arraylist being sorted into a new jlist....
Sorry if that sounds confusing...
here is an example
arraylist data unsorted on jlist A
George 34567
Peter 23456
Sam 12345
User now selects speed of items added to jlist (ie 5 seconds)
arraylist data sorted on jlist B
George 12345 (every 5 seconds a name enters the list)
Peter 23456
Sam 34567
So far i cant seem to get the bubblesort method in my add to system.out.println the sorted data.
Sorry if that sounds confusing...
here is an example
arraylist data unsorted on jlist A
George 34567
Peter 23456
Sam 12345
User now selects speed of items added to jlist (ie 5 seconds)
arraylist data sorted on jlist B
George 12345 (every 5 seconds a name enters the list)
Peter 23456
Sam 34567
So far i cant seem to get the bubblesort method in my add to system.out.println the sorted data.
•
•
Join Date: Oct 2008
Posts: 103
Reputation:
Solved Threads: 14
Please post more information about the requirements for your program. Also more about how the data should look during different stages of the program execution as well as explanations as to why the data should look that way. It'd also be nice if you could show how the data is supposed to look (or how you think it looks) inside the arraylist (including data types).
![]() |
Similar Threads
- Spilt text and parse to arraylist (Java)
- Writing ArrayList to textFile? (C#)
- A continuation of my Coin Purse problem plz help ive been working on this for 6 hrs (Java)
- Sorting a List of Items (Java)
- Sorting (Java)
- Sorting (Java)
- ArrayList from something other than primitives (C#)
- Sorting in C++ (C++)
- Need Help with ArrayList sorting (Java)
- Linked arraylist (Java)
Other Threads in the Java Forum
- Previous Thread: Dezign for Database
- Next Thread: can someone help me complete this program.. its giving me a head ache...
| Thread Tools | Search this Thread |
Tag cloud for Java
android api apple applet application arc arguments array arrays automation binary bluetooth c++ chat class classes client code codesnippet component csv database doctype draw ebook eclipse error event exception fractal freeze game givemetehcodez graphics gui html ide image input integer intellij iphone j2me java java.xls javaprojects jmf jni jpanel julia linux list loop loops mac map method methods mobile netbeans newbie number online oracle page parameter plazmic print problem program programming project recursion reporting rotatetext scanner screen sell server set size sms socket sort sourcelabs sql string superclass swing system template test testautomation threads time title tree tutorial-sample windows working






