Source Code that don't work?

Reply

Join Date: Mar 2005
Posts: 13
Reputation: buggytoast is an unknown quantity at this point 
Solved Threads: 0
buggytoast buggytoast is offline Offline
Newbie Poster

Source Code that don't work?

 
0
  #1
Apr 1st, 2006
Hey guys!

My program implements the vector class however it only shows I know how to use the Vector Class, and not how to develop a code for a linked list My teacher says I can just do a copy paste job, which is precisely what I did. But for some strange reason it still doesn't work. Does anyone know whats wrong?

Here are the java classes that make the program run.

Here's the main
  1. // Philip Kao
  2. // IB Comsci Dossier
  3. // TreeClassics Program
  4. import java.io.*;
  5. import java.awt.*;
  6. import java.awt.event.*;
  7. import javax.swing.*;
  8. import java.util.*;
  9.  
  10. public class TreeClassics extends JFrame
  11. {
  12. //include aspects of GUI
  13. private JTextField quantityField, thicknessField, widthField,
  14. plysField, modelField, heightField, tipField, groupField;
  15. // modelField, heightField, tipField, groupField have not been
  16. // implemented yet; for panel 3
  17. //
  18. private JEditorPane scrollListContent;
  19. private JTextArea enteredContent;
  20. private JList enteredItemsList, loadedList;
  21.  
  22. // Labels for field input identifier
  23. private JLabel quantityLabel, thicknessLabel,
  24. widthLabel, colorLabel, plysLabel,
  25. productionLabel, informLabel, specifyLabel,
  26. plys1Label, color1Label, quantity1Label,
  27. model1Label, thickness1Label, width1Label,
  28. helper1Label, helper2Label, helper3Label,
  29. helper4Label, helper5Label;
  30.  
  31. // The three tab panels
  32. private JPanel panel1, panel2, panel3;
  33.  
  34. // Combobox selection system
  35. private JComboBox modelComboBox, colorComboBox;
  36.  
  37. private JScrollPane orderScrollPane, enteredScrollPane;
  38.  
  39. private JButton
  40. loadModelsButton, enterButton, removeTempItemsButton,
  41. saveListButton, deleteModelsButton, modelInfoButton,
  42. modelButton, thicknessButton, widthButton, colorButton,
  43. loadListButton;
  44.  
  45. private javax.swing.JButton clearListButton, // NOTE: saveModelB, loadModelB, delModelB pertain to the
  46. saveModelB, loadModelB, delModelB;
  47. private Vector<Model> modelList;
  48. private String[] colors = {"Green", "Teal", "Dark Blue", "White", "Gray"};
  49. private OrderList prodList;
  50.  
  51. private TreeClassics()
  52. {
  53. // GUI Setup for program
  54. super("Tree Classics Production Line");
  55.  
  56. this.prodList = new OrderList();
  57. this.modelList = new Vector<Model>();
  58.  
  59. // Creating JTabbed Pane
  60. JTabbedPane tabbedPane = new JTabbedPane();
  61.  
  62. // -------------------------PANEL 1 INTERFACE---------------------------
  63. // Set up Panel 1
  64. JLabel label1 = new JLabel();
  65. panel1 = new JPanel( null );
  66. panel1.add( label1 );
  67. tabbedPane.addTab( " Production Order ",
  68. null, panel1, "Production orders are created here");
  69.  
  70. // Model number selection label
  71. productionLabel = new JLabel( "Model Number");
  72. productionLabel.setBounds( 20, 20, 100, 20 );
  73. panel1.add( productionLabel );
  74.  
  75. // Add Combo Box into Panel 1: PRODUCTION ORDER
  76. modelComboBox = new JComboBox();
  77. modelComboBox.setBounds(20, 40, 150, 20);
  78. panel1.add(modelComboBox);
  79.  
  80. // Add Help Button into Panel1
  81. modelInfoButton = new JButton( "Model Information" );
  82. modelInfoButton.setBounds( 20, 70, 150, 20);
  83. panel1.add(modelInfoButton);
  84.  
  85. // Titles for Selection and treeData types
  86. // Quantity
  87. quantityLabel = new JLabel( "Quantity");
  88. quantityLabel.setBounds( 250, 20, 100, 20 );
  89. panel1.add(quantityLabel);
  90.  
  91. // Thickness
  92. thicknessLabel = new JLabel( "Thickness");
  93. thicknessLabel.setBounds( 250, 75, 100, 20 );
  94. panel1.add(thicknessLabel);
  95.  
  96. // Width
  97. widthLabel = new JLabel( "Width");
  98. widthLabel.setBounds( 370, 20, 100, 20 );
  99. panel1.add(widthLabel);
  100.  
  101. // Color
  102. colorLabel = new JLabel( "Color");
  103. colorLabel.setBounds( 490, 20, 100, 20 );
  104. panel1.add(colorLabel);
  105.  
  106. // Plys
  107. plysLabel = new JLabel( "Plys");
  108. plysLabel.setBounds( 370, 75, 100, 20 );
  109. panel1.add( plysLabel );
  110.  
  111. // Color 1 Label
  112. color1Label = new JLabel( "Color");
  113. color1Label.setBounds( 320, 130, 100, 20 );
  114. panel1.add(color1Label);
  115.  
  116. // Models 1 Label
  117. model1Label = new JLabel( "Model Number");
  118. model1Label.setBounds( 20, 130, 100, 20 );
  119. panel1.add(model1Label);
  120.  
  121. // quantity 1 Label
  122. quantity1Label = new JLabel( "Quantity");
  123. quantity1Label.setBounds( 120, 130, 100, 20 );
  124. panel1.add(quantity1Label);
  125.  
  126. // thickness 1 Label
  127. thickness1Label = new JLabel( "Thickness");
  128. thickness1Label.setBounds( 185, 130, 100, 20 );
  129. panel1.add(thickness1Label);
  130.  
  131. // width 1 Label
  132. width1Label = new JLabel( "Width");
  133. width1Label.setBounds( 260, 130, 100, 20 );
  134. panel1.add(width1Label);
  135.  
  136. // plys 1 Label
  137. plys1Label = new JLabel( "Plys");
  138. plys1Label.setBounds( 370, 130, 100, 20 );
  139. panel1.add(plys1Label);
  140.  
  141. // Quantity field input
  142. quantityField = new JTextField();
  143. quantityField = new JTextField("0", 15 );
  144. quantityField.setBounds( 250, 40 , 100, 20);
  145. panel1.add( quantityField );
  146.  
  147. // Width field input
  148. widthField = new JTextField();
  149. widthField = new JTextField("0", 15 );
  150. widthField.setBounds( 370, 40 , 100, 20);
  151. panel1.add( widthField );
  152.  
  153. // Thickness field input
  154. thicknessField = new JTextField();
  155. thicknessField = new JTextField("0", 15 );
  156. thicknessField.setBounds( 250, 95 , 100, 20);
  157. panel1.add(thicknessField);
  158.  
  159. // Plys field input
  160. plysField = new JTextField();
  161. plysField = new JTextField("0", 15 );
  162. plysField.setBounds( 370, 95 , 100, 20);
  163. panel1.add(plysField);
  164.  
  165. // Color scroll pane input
  166. colorComboBox = new JComboBox( colors );
  167. colorComboBox.setMaximumRowCount( 5 );
  168. colorComboBox.setBounds( 490, 40, 100, 20 );
  169. colorComboBox.setSelectedIndex( 0 );
  170. panel1.add(colorComboBox);
  171.  
  172. // Panel 1 scroll pane for entered information
  173. //enteredContent = new JTextArea();
  174. //enteredContent.setEditable(false);
  175. enteredItemsList = new JList(prodList);
  176. enteredScrollPane = new JScrollPane(enteredItemsList);
  177. enteredScrollPane.setBounds(20,150,400,150);
  178. enteredScrollPane.createVerticalScrollBar();
  179. panel1.add(enteredScrollPane);
  180.  
  181. // Add Enter Button into Panel1
  182. enterButton = new JButton("Enter");
  183. enterButton.setBounds( 450, 150 , 100, 20);
  184. panel1.add(enterButton);
  185.  
  186. removeTempItemsButton = new JButton("Remove Selected");
  187. removeTempItemsButton.setBounds( 450, 180 , 150, 20);
  188. panel1.add(removeTempItemsButton);
  189.  
  190. // Add Save Button into Panel1
  191. saveListButton = new JButton( "Save List" );
  192. saveListButton.setBounds( 450, 210 , 150, 20);
  193. panel1.add(saveListButton);
  194.  
  195. // Add load model button into Panel1
  196. loadModelsButton = new JButton("Load Model Set");
  197. loadModelsButton.setBounds( 450, 240, 150, 20);
  198. panel1.add( loadModelsButton);
  199.  
  200. // Add delete model button into Panel1
  201. deleteModelsButton = new JButton("Delete Model Set");
  202. deleteModelsButton.setBounds( 450, 270, 150, 20);
  203. panel1.add(deleteModelsButton);
  204.  
  205. // ------------------PANEL 2 INTERFACE----------------------------------
  206. // Set up Panel 2
  207. JLabel label2 = new JLabel( "Panel Two", SwingConstants.CENTER );
  208. panel2 = new JPanel( null );
  209. panel2.add( label2 );
  210. tabbedPane.addTab( " List Orders ",
  211. null, panel2, "Orders are listed and organized here");
  212.  
  213. // Add Infomer Label into Panel 2
  214. informLabel = new JLabel( "Information of this list");
  215. informLabel.setBounds( 40, 20, 300, 20 );
  216. panel2.add( informLabel );
  217.  
  218. // Add scroll pane label into Panel 2
  219. informLabel = new JLabel( "Model Quantity Thickness Width Color Plys");
  220. informLabel.setBounds( 20, 60, 400, 20 );
  221. panel2.add( informLabel );
  222.  
  223. // Panel 2 scroll pane
  224. scrollListContent = new JEditorPane();
  225. scrollListContent.setEditable(false);
  226. orderScrollPane = new JScrollPane(scrollListContent);
  227. orderScrollPane.setBounds(20,80,400,220);
  228. orderScrollPane.createVerticalScrollBar();
  229. panel2.add(orderScrollPane);
  230.  
  231. // Add Sort by Model Button into Panel2
  232. modelButton = new JButton( "Sort by Model #" );
  233. modelButton.setBounds( 450, 80 , 150, 20);
  234. panel2.add( modelButton );
  235.  
  236. // Add Sort by Thickness Button into Panel2
  237. thicknessButton = new JButton( "Sort by Thickness" );
  238. thicknessButton.setBounds( 450, 170 , 150, 20);
  239. panel2.add( thicknessButton );
  240.  
  241. // Add Sort by Width Button into Panel2
  242. widthButton = new JButton( "Sort by Width" );
  243. widthButton.setBounds( 450, 110 , 150, 20);
  244. panel2.add( widthButton );
  245.  
  246. // Add Sort by Color Button into Panel2
  247. colorButton = new JButton( "Sort by Color" );
  248. colorButton.setBounds( 450, 140 , 150, 20);
  249. panel2.add( colorButton );
  250.  
  251. // Add Load Button into Panel2
  252. loadListButton = new JButton( "Load List" );
  253. loadListButton.setBounds( 450, 200 , 150, 20);
  254. panel2.add(loadListButton);
  255.  
  256. // Add Clear Button into Panel2
  257. clearListButton = new JButton( "Clear List" );
  258. clearListButton.setBounds( 450, 230 , 150, 20);
  259. panel2.add(clearListButton);
  260.  
  261. // ------------------PANEL 3 INTERFACE----------------------------------
  262. // Set up Panel 3: For Printing
  263. JLabel label3 = new JLabel( "Panel Three", SwingConstants.CENTER );
  264. panel3 = new JPanel( null );
  265. panel3.add( label3 );
  266. tabbedPane.addTab( " HELP PANEL ",
  267. null, panel3, "Select the set of data of models to use");
  268.  
  269. // Add Specify Label into Panel 3
  270. specifyLabel = new JLabel( "WELCOME TO THE HELP MENU!");
  271. specifyLabel.setBounds( 40, 20, 200, 20 );
  272. panel3.add( specifyLabel );
  273.  
  274. // Add Helper Label into Panel 3
  275. helper1Label = new JLabel( "Follow these steps and you \n won't have any problem using the program!");
  276. helper1Label.setBounds( 40, 50, 400, 20 );
  277. panel3.add( helper1Label );
  278.  
  279. // Add Helper2 Label into Panel 3
  280. helper2Label = new JLabel( "Step 1. Load Model set");
  281. helper2Label.setBounds( 40, 80, 400, 20 );
  282. panel3.add( helper2Label );
  283.  
  284. // Add Helper2 Label into Panel 3
  285. helper3Label = new JLabel( "Step 2. Fill in necessary fields of input");
  286. helper3Label.setBounds( 40, 110, 400, 20 );
  287. panel3.add( helper3Label );
  288.  
  289. // Add Helper2 Label into Panel 3
  290. helper4Label = new JLabel( "Step 3. Save/Remove List of inputs");
  291. helper4Label.setBounds( 40, 80, 400, 20 );
  292. panel3.add( helper4Label );
  293.  
  294.  
  295.  
  296. getContentPane().add( tabbedPane );
  297. setSize( 640, 400 );
  298. setVisible(true);
  299.  
  300. //Panel 1 handlers------------------------------------------------------
  301. // Help button to check fields entry
  302. modelInfoButton.addActionListener (
  303. new ActionListener()
  304. { public void actionPerformed( ActionEvent e) {showModelInfo();} }
  305. );
  306.  
  307. // Enter button to check fields entry
  308. enterButton.addActionListener (
  309. new ActionListener()
  310. { public void actionPerformed(ActionEvent e) {readInput();} }
  311. );
  312.  
  313. // button to remove selected items from temp list
  314. removeTempItemsButton.addActionListener (
  315. new ActionListener()
  316. { public void actionPerformed(ActionEvent e) {removeTempItems();} }
  317. );
  318.  
  319. // Save button call
  320. saveListButton.addActionListener (
  321. new ActionListener()
  322. { public void actionPerformed(ActionEvent e) {saveList();} }
  323. );
  324.  
  325. // Load button call
  326. loadModelsButton.addActionListener(
  327. new ActionListener()
  328. { public void actionPerformed(ActionEvent e) {loadModels();} }
  329. );
  330.  
  331. // Clear button
  332. deleteModelsButton.addActionListener (
  333. new ActionListener()
  334. { public void actionPerformed( ActionEvent e) {deleteModels();} }
  335. );
  336.  
  337. //Panel 2 handlers------------------------------------------------------
  338. // Load button call
  339. loadListButton.addActionListener(
  340. new ActionListener()
  341. { public void actionPerformed(ActionEvent e) {openList();} }
  342. );
  343.  
  344. // Clear button
  345. clearListButton.addActionListener (
  346. new ActionListener()
  347. { public void actionPerformed(ActionEvent e) {clearList();} }
  348. );
  349.  
  350. // Sort by model button
  351. modelButton.addActionListener (
  352. new ActionListener()
  353. {
  354. public void actionPerformed(ActionEvent e) {prodList.sort(0);
  355. scrollListContent.setText(prodList.toString());
  356. } }
  357. );
  358.  
  359. // Sort by thickness button
  360. modelButton.addActionListener (
  361. new ActionListener()
  362. {
  363. public void actionPerformed(ActionEvent e) {prodList.sort(1);
  364. scrollListContent.setText(prodList.toString());
  365. } }
  366. );
  367.  
  368. // Width sort button
  369. widthButton.addActionListener (
  370. new ActionListener()
  371. {
  372. public void actionPerformed(ActionEvent e) {prodList.sort(2);
  373. scrollListContent.setText(prodList.toString());
  374. } }
  375. );
  376.  
  377. // Color sort button
  378. colorButton.addActionListener (
  379. new ActionListener()
  380. {
  381. public void actionPerformed(ActionEvent e) {prodList.sort(3);
  382. scrollListContent.setText(prodList.toString());
  383. } }
  384. );
  385. }
  386.  
  387. //read from input fields, then add item to list
  388. private void readInput()
  389. {
  390. String modelNo = (String)(modelComboBox.getSelectedItem());
  391. if (modelNo == null) return;
  392. try {
  393. int quantity = Integer.parseInt(quantityField.getText());
  394. double thickness = Double.parseDouble(thicknessField.getText());
  395. double width = Double.parseDouble(widthField.getText());
  396. String color = (String)(colorComboBox.getSelectedItem());
  397. double plys = Double.parseDouble(plysField.getText());
  398.  
  399. if (quantity < 0 || thickness < 0 || width < 0 || plys < 0)
  400. throw new NumberFormatException("Negative attributes");
  401. prodList.add(
  402. new TreeData(modelNo, quantity, thickness, width, color, plys));
  403.  
  404. // Repaints the scroll pane to display newly entered data
  405. enteredItemsList.setListData(prodList);
  406. }
  407. catch (NumberFormatException e)
  408. { JOptionPane.showMessageDialog(this, "At least 1 field is illegal",
  409. "Error", JOptionPane.ERROR_MESSAGE ); }
  410. }
  411.  
  412. private void removeTempItems()
  413. {
  414. int[] select = enteredItemsList.getSelectedIndices();
  415. for (int i = select.length-1; i >= 0; i--)
  416. {
  417. int selectIndex = select[i];
  418. if (selectIndex < 0) return;
  419. prodList.removeElementAt(selectIndex);
  420. enteredItemsList.removeSelectionInterval(selectIndex, selectIndex);
  421. enteredItemsList.repaint();
  422. }
  423. }
  424.  
  425. //pop up a window showing model info
  426. private void showModelInfo()
  427. {
  428. JOptionPane.showMessageDialog( null, "Always remember to load model info \n Create a text file using this template \n 48-209-351 1.3 300 \n 560-344-351 1.45 250 12 \n 72-554-351 1.32 200 9 \n 84-754-351 1.35 350 3 \n 96-1042-351 1.4 280 7",
  429. "REMINDER", JOptionPane.PLAIN_MESSAGE );
  430. }
  431.  
  432. /**
  433.   * CLEAR FILE
  434.   * Clears the scroll list pane in the 2nd panel
  435.   */
  436. private void clearList()
  437. {
  438. this.prodList = null; //Cleanup by garbage collector
  439. scrollListContent.setText("No list loaded.");
  440. panel2.repaint();
  441. }
  442.  
  443. /**
  444.   * OPEN FILE
  445.   * Opens
  446.   */
  447. private void openList()
  448. {
  449. File inFile = chooseFile(false);
  450. if (inFile == null) return;
  451.  
  452. prodList = new OrderList(inFile, this);
  453. scrollListContent.setText(prodList.toString());
  454. //panel2.repaint();
  455. }
  456.  
  457. //save list to file
  458. private void saveList()
  459. {
  460. if (prodList.size() == 0) {
  461. JOptionPane.showMessageDialog(this, "There is nothing to save",
  462. "ERROR", JOptionPane.ERROR_MESSAGE );
  463. return;
  464. }
  465.  
  466. File outFile = chooseFile(true);
  467. if (outFile == null) return;
  468. if (outFile.exists())
  469. if (JOptionPane.showConfirmDialog(this,
  470. "File " + outFile.getName() + " already exists. Overwrite?",
  471. "WARNING", JOptionPane.YES_NO_OPTION,
  472. JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION)
  473. return;
  474.  
  475. try {
  476. FileWriter output = new FileWriter(outFile);
  477. String toWrite = prodList.toString();
  478. output.write(toWrite, 0, toWrite.length());
  479. output.flush();
  480. output.close();
  481. }
  482. catch (IOException e)
  483. { JOptionPane.showMessageDialog(this, "File cannot be saved",
  484. "ERROR", JOptionPane.ERROR_MESSAGE ); }
  485. }
  486.  
  487. //load list of available models to combo box
  488. private void loadModels()
  489. {
  490. File inFile = chooseFile(false);
  491. if (inFile == null) return;
  492. try {
  493. if (!(inFile.exists()))
  494. throw new IOException("File does not exist");
  495. modelComboBox.removeAllItems(); //clean up before adding
  496. Scanner in = new Scanner(inFile);
  497. while (in.hasNextLine()) {
  498. Scanner lineScanner = new Scanner(in.nextLine());
  499. try {
  500. String modelID = lineScanner.next();
  501. double height = lineScanner.nextDouble();
  502. int tipNum = lineScanner.nextInt();
  503. int group = lineScanner.nextInt();
  504. modelList.add(new Model(modelID, height, tipNum, group));
  505. modelComboBox.addItem(modelID);
  506. }
  507. catch (NoSuchElementException e) { continue; }
  508. }
  509. }
  510. catch (IOException e)
  511. { JOptionPane.showMessageDialog(this, "Error loading file",
  512. "Error", JOptionPane.ERROR_MESSAGE); }
  513. }
  514.  
  515. private File chooseFile(boolean saveDialog)
  516. {
  517. JFileChooser fileChooser = new JFileChooser();
  518. fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
  519.  
  520. // open file chooser; if user clicked Cancel then return null
  521. int chooserDialogReturn;
  522. if (saveDialog)
  523. chooserDialogReturn = fileChooser.showSaveDialog(this);
  524. else
  525. chooserDialogReturn = fileChooser.showOpenDialog(this);
  526. if (chooserDialogReturn == JFileChooser.CANCEL_OPTION)
  527. return null;
  528.  
  529. return fileChooser.getSelectedFile(); // get selected file
  530. }
  531.  
  532. //clear model dropdown list
  533. private void deleteModels()
  534. {
  535. modelList.removeAllElements();
  536. modelComboBox.removeAllItems();
  537. }
  538.  
  539. //================================MAIN======================================
  540.  
  541. public static void main(String args[])
  542. {
  543. TreeClassics tabbedPane = new TreeClassics();
  544. tabbedPane.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  545. }
  546. }

  1. /**
  2.  * The TreeData class
  3.  * @author Philip Kao
  4.  * @version 5/2/06
  5.  * IB Comsci Dossier: TreeClassics program
  6.  */
  7. public class TreeData
  8. {
  9. private String modelNo; // Tree model number (Format: XX-XXX-XXX)
  10. private int quantity; // Quantity of desired tree model
  11. private double thickness; // Thickness of plys needed for each tree (mm)
  12. private double width;
  13. private String color;
  14. private double plys;
  15.  
  16. // Class constructor (blank data)
  17. public TreeData()
  18. {}
  19.  
  20. // Class constructor (new data)
  21. public TreeData(String modelNo, int quantity, double thickness,
  22. double width, String color, double plys)
  23. {
  24. setModelNo(modelNo);
  25. setQuantity(quantity);
  26. setThickness(thickness);
  27. setWidth(width);
  28. setColor(color);
  29. setPlys(plys);
  30. }
  31.  
  32. public void setQuantity(int quantity)
  33. {this.quantity = quantity; }
  34.  
  35. public int getQuantity()
  36. {return quantity; }
  37.  
  38. public void setModelNo(String modelNo)
  39. {this.modelNo = modelNo;}
  40.  
  41. public String getModelNo()
  42. {return modelNo;}
  43.  
  44. public void setThickness(double thickness)
  45. {this.thickness = thickness;}
  46.  
  47. public double getThickness()
  48. {return thickness;}
  49.  
  50. public void setWidth(double width)
  51. {this.width = width;}
  52.  
  53. public double getWidth()
  54. {return width;}
  55.  
  56. public void setColor(String color)
  57. {this.color = color;}
  58.  
  59. public String getColor()
  60. {return color;}
  61.  
  62. public void setPlys(double plys)
  63. {this.plys = plys;}
  64.  
  65. public double getPlys()
  66. {return plys;}
  67.  
  68. public String toString()
  69. {
  70. return modelNo + "\t" + quantity + "\t" + thickness + "\t" + width +
  71. "\t" + color + "\t" + plys;
  72. }
  73.  
  74. public boolean equals(Object o)
  75. {
  76. if (!(o instanceof TreeData))
  77. throw new IllegalArgumentException("Wrong type: expects TreeData");
  78.  
  79. TreeData item = (TreeData)o;
  80. if (item.modelNo == modelNo &&
  81. item.thickness == thickness &&
  82. item.width == width &&
  83. item.color.equals(color) &&
  84. item.plys == plys)
  85. return true;
  86. else
  87. return false;
  88. }
  89. }

  1. public class Model
  2. {
  3. private String modelNo;
  4. private double height;
  5. private int tipNum;
  6. private int group;
  7.  
  8. // Blank constructor
  9. public Model()
  10. {}
  11.  
  12. // Enter values for model information
  13. public Model(String modelNo, double height, int tipNum, int group)
  14. {
  15. setModelNo(modelNo);
  16. setHeight(height);
  17. setTipNum(tipNum);
  18. setGroup(group);
  19. }
  20.  
  21. // Model number methods
  22. public void setModelNo(String modelNo)
  23. {this.modelNo = modelNo;}
  24.  
  25. public String getModelNo()
  26. {return modelNo;}
  27.  
  28. // Height methods
  29. public void setHeight(double height)
  30. {this.height = height;}
  31.  
  32. public double getHeight()
  33. {return height;}
  34.  
  35. // tipNum methods
  36. public void setTipNum(int tipNum)
  37. {this.tipNum = tipNum;}
  38.  
  39. public int getTipNum()
  40. {return tipNum;}
  41.  
  42. // group methods
  43. public void setGroup(int group)
  44. {this.group = group;}
  45.  
  46. public int getGroup()
  47. {return group;}
  48. }

  1. /*
  2.  * @(#)LinkedList.java 1.96 04/02/19
  3.  *
  4.  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5.  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6.  */
  7. package java.util;
  8.  
  9. /**
  10.  * The <code>LinkedList</code> class implements a growable array of
  11.  * objects. Like an array, it contains components that can be
  12.  * accessed using an integer index. However, the size of a
  13.  * <code>LinkedList</code> can grow or shrink as needed to accommodate
  14.  * adding and removing items after the <code>LinkedList</code> has been created.<p>
  15.  *
  16.  * Each LinkedList tries to optimize storage management by maintaining a
  17.  * <code>capacity</code> and a <code>capacityIncrement</code>. The
  18.  * <code>capacity</code> is always at least as large as the LinkedList
  19.  * size; it is usually larger because as components are added to the
  20.  * LinkedList, the LinkedList's storage increases in chunks the size of
  21.  * <code>capacityIncrement</code>. An application can increase the
  22.  * capacity of a LinkedList before inserting a large number of
  23.  * components; this reduces the amount of incremental reallocation. <p>
  24.  *
  25.  * As of the Java 2 platform v1.2, this class has been retrofitted to
  26.  * implement List, so that it becomes a part of Java's collection framework.
  27.  * Unlike the new collection implementations, LinkedList is synchronized.<p>
  28.  *
  29.  * The Iterators returned by LinkedList's iterator and listIterator
  30.  * methods are <em>fail-fast</em>: if the LinkedList is structurally modified
  31.  * at any time after the Iterator is created, in any way except through the
  32.  * Iterator's own remove or add methods, the Iterator will throw a
  33.  * ConcurrentModificationException. Thus, in the face of concurrent
  34.  * modification, the Iterator fails quickly and cleanly, rather than risking
  35.  * arbitrary, non-deterministic behavior at an undetermined time in the future.
  36.  * The Enumerations returned by LinkedList's elements method are <em>not</em>
  37.  * fail-fast.
  38.  *
  39.  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  40.  * as it is, generally speaking, impossible to make any hard guarantees in the
  41.  * presence of unsynchronized concurrent modification. Fail-fast iterators
  42.  * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
  43.  * Therefore, it would be wrong to write a program that depended on this
  44.  * exception for its correctness: <i>the fail-fast behavior of iterators
  45.  * should be used only to detect bugs.</i><p>
  46.  *
  47.  * This class is a member of the
  48.  * <a href="{@docRoot}/../guide/collections/index.html">
  49.  * Java Collections Framework</a>.
  50.  *
  51.  * @author Lee Boynton
  52.  * @author Jonathan Payne
  53.  * @version 1.96, 02/19/04
  54.  * @see Collection
  55.  * @see List
  56.  * @see ArrayList
  57.  * @see LinkedList
  58.  * @since JDK1.0
  59.  */
  60. public class LinkedList<E>
  61. extends AbstractList<E>
  62. implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  63. {
  64. /**
  65.   * The array buffer into which the components of the LinkedList are
  66.   * stored. The capacity of the LinkedList is the length of this array buffer,
  67.   * and is at least large enough to contain all the LinkedList's elements.<p>
  68.   *
  69.   * Any array elements following the last element in the LinkedList are null.
  70.   *
  71.   * @serial
  72.   */
  73. protected Object[] elementData;
  74.  
  75. /**
  76.   * The number of valid components in this <tt>LinkedList</tt> object.
  77.   * Components <tt>elementData[0]</tt> through
  78.   * <tt>elementData[elementCount-1]</tt> are the actual items.
  79.   *
  80.   * @serial
  81.   */
  82. protected int elementCount;
  83.  
  84. /**
  85.   * The amount by which the capacity of the LinkedList is automatically
  86.   * incremented when its size becomes greater than its capacity. If
  87.   * the capacity increment is less than or equal to zero, the capacity
  88.   * of the LinkedList is doubled each time it needs to grow.
  89.   *
  90.   * @serial
  91.   */
  92. protected int capacityIncrement;
  93.  
  94. /** use serialVersionUID from JDK 1.0.2 for interoperability */
  95. private static final long serialVersionUID = -2767605614048989439L;
  96.  
  97. /**
  98.   * Constructs an empty LinkedList with the specified initial capacity and
  99.   * capacity increment.
  100.   *
  101.   * @param initialCapacity the initial capacity of the LinkedList.
  102.   * @param capacityIncrement the amount by which the capacity is
  103.   * increased when the LinkedList overflows.
  104.   * @exception IllegalArgumentException if the specified initial capacity
  105.   * is negative
  106.   */
  107. public LinkedList(int initialCapacity, int capacityIncrement) {
  108. super();
  109. if (initialCapacity < 0)
  110. throw new IllegalArgumentException("Illegal Capacity: "+
  111. initialCapacity);
  112. this.elementData = new Object[initialCapacity];
  113. this.capacityIncrement = capacityIncrement;
  114. }
  115.  
  116. /**
  117.   * Constructs an empty LinkedList with the specified initial capacity and
  118.   * with its capacity increment equal to zero.
  119.   *
  120.   * @param initialCapacity the initial capacity of the LinkedList.
  121.   * @exception IllegalArgumentException if the specified initial capacity
  122.   * is negative
  123.   */
  124. public LinkedList(int initialCapacity) {
  125. this(initialCapacity, 0);
  126. }
  127.  
  128. /**
  129.   * Constructs an empty LinkedList so that its internal data array
  130.   * has size <tt>10</tt> and its standard capacity increment is
  131.   * zero.
  132.   */
  133. public LinkedList() {
  134. this(10);
  135. }
  136.  
  137. /**
  138.   * Constructs a LinkedList containing the elements of the specified
  139.   * collection, in the order they are returned by the collection's
  140.   * iterator.
  141.   *
  142.   * @param c the collection whose elements are to be placed into this
  143.   * LinkedList.
  144.   * @throws NullPointerException if the specified collection is null.
  145.   * @since 1.2
  146.   */
  147. public LinkedList(Collection<? extends E> c) {
  148. elementCount = c.size();
  149. // 10% for growth
  150. elementData = new Object[
  151. (int)Math.min((elementCount*110L)/100,Integer.MAX_VALUE)];
  152. c.toArray(elementData);
  153. }
  154.  
  155. /**
  156.   * Copies the components of this LinkedList into the specified array. The
  157.   * item at index <tt>k</tt> in this LinkedList is copied into component
  158.   * <tt>k</tt> of <tt>anArray</tt>. The array must be big enough to hold
  159.   * all the objects in this LinkedList, else an
  160.   * <tt>IndexOutOfBoundsException</tt> is thrown.
  161.   *
  162.   * @param anArray the array into which the components get copied.
  163.   * @throws NullPointerException if the given array is null.
  164.   */
  165. public synchronized void copyInto(Object[] anArray) {
  166. System.arraycopy(elementData, 0, anArray, 0, elementCount);
  167. }
  168.  
  169. /**
  170.   * Trims the capacity of this LinkedList to be the LinkedList's current
  171.   * size. If the capacity of this LinkedList is larger than its current
  172.   * size, then the capacity is changed to equal the size by replacing
  173.   * its internal data array, kept in the field <tt>elementData</tt>,
  174.   * with a smaller one. An application can use this operation to
  175.   * minimize the storage of a LinkedList.
  176.   */
  177. public synchronized void trimToSize() {
  178. modCount++;
  179. int oldCapacity = elementData.length;
  180. if (elementCount < oldCapacity) {
  181. Object oldData[] = elementData;
  182. elementData = new Object[elementCount];
  183. System.arraycopy(oldData, 0, elementData, 0, elementCount);
  184. }
  185. }
  186.  
  187. /**
  188.   * Increases the capacity of this LinkedList, if necessary, to ensure
  189.   * that it can hold at least the number of components specified by
  190.   * the minimum capacity argument.
  191.   *
  192.   * <p>If the current capacity of this LinkedList is less than
  193.   * <tt>minCapacity</tt>, then its capacity is increased by replacing its
  194.   * internal data array, kept in the field <tt>elementData</tt>, with a
  195.   * larger one. The size of the new data array will be the old size plus
  196.   * <tt>capacityIncrement</tt>, unless the value of
  197.   * <tt>capacityIncrement</tt> is less than or equal to zero, in which case
  198.   * the new capacity will be twice the old capacity; but if this new size
  199.   * is still smaller than <tt>minCapacity</tt>, then the new capacity will
  200.   * be <tt>minCapacity</tt>.
  201.   *
  202.   * @param minCapacity the desired minimum capacity.
  203.   */
  204. public synchronized void ensureCapacity(int minCapacity) {
  205. modCount++;
  206. ensureCapacityHelper(minCapacity);
  207. }
  208.  
  209. /**
  210.   * This implements the unsynchronized semantics of ensureCapacity.
  211.   * Synchronized methods in this class can internally call this
  212.   * method for ensuring capacity without incurring the cost of an
  213.   * extra synchronization.
  214.   *
  215.   * @see java.util.LinkedList#ensureCapacity(int)
  216.   */
  217. private void ensureCapacityHelper(int minCapacity) {
  218. int oldCapacity = elementData.length;
  219. if (minCapacity > oldCapacity) {
  220. Object[] oldData = elementData;
  221. int newCapacity = (capacityIncrement > 0) ?
  222. (oldCapacity + capacityIncrement) : (oldCapacity * 2);
  223. if (newCapacity < minCapacity) {
  224. newCapacity = minCapacity;
  225. }
  226. elementData = new Object[newCapacity];
  227. System.arraycopy(oldData, 0, elementData, 0, elementCount);
  228. }
  229. }
  230.  
  231. /**
  232.   * Sets the size of this LinkedList. If the new size is greater than the
  233.   * current size, new <code>null</code> items are added to the end of
  234.   * the LinkedList. If the new size is less than the current size, all
  235.   * components at index <code>newSize</code> and greater are discarded.
  236.   *
  237.   * @param newSize the new size of this LinkedList.
  238.   * @throws ArrayIndexOutOfBoundsException if new size is negative.
  239.   */
  240. public synchronized void setSize(int newSize) {
  241. modCount++;
  242. if (newSize > elementCount) {
  243. ensureCapacityHelper(newSize);
  244. } else {
  245. for (int i = newSize ; i < elementCount ; i++) {
  246. elementData[i] = null;
  247. }
  248. }
  249. elementCount = newSize;
  250. }
  251.  
  252. /**
  253.   * Returns the current capacity of this LinkedList.
  254.   *
  255.   * @return the current capacity (the length of its internal
  256.   * data array, kept in the field <tt>elementData</tt>
  257.   * of this LinkedList).
  258.   */
  259. public synchronized int capacity() {
  260. return elementData.length;
  261. }
  262.  
  263. /**
  264.   * Returns the number of components in this LinkedList.
  265.   *
  266.   * @return the number of components in this LinkedList.
  267.   */
  268. public synchronized int size() {
  269. return elementCount;
  270. }
  271.  
  272. /**
  273.   * Tests if this LinkedList has no components.
  274.   *
  275.   * @return <code>true</code> if and only if this LinkedList has
  276.   * no components, that is, its size is zero;
  277.   * <code>false</code> otherwise.
  278.   */
  279. public synchronized boolean isEmpty() {
  280. return elementCount == 0;
  281. }
  282.  
  283. /**
  284.   * Returns an enumeration of the components of this LinkedList. The
  285.   * returned <tt>Enumeration</tt> object will generate all items in
  286.   * this LinkedList. The first item generated is the item at index <tt>0</tt>,
  287.   * then the item at index <tt>1</tt>, and so on.
  288.   *
  289.   * @return an enumeration of the components of this LinkedList.
  290.   * @see Enumeration
  291.   * @see Iterator
  292.   */
  293. public Enumeration<E> elements() {
  294. return new Enumeration<E>() {
  295. int count = 0;
  296.  
  297. public boolean hasMoreElements() {
  298. return count < elementCount;
  299. }
  300.  
  301. public E nextElement() {
  302. synchronized (LinkedList.this) {
  303. if (count < elementCount) {
  304. return (E)elementData[count++];
  305. }
  306. }
  307. throw new NoSuchElementException("LinkedList Enumeration");
  308. }
  309. };
  310. }
  311.  
  312. /**
  313.   * Tests if the specified object is a component in this LinkedList.
  314.   *
  315.   * @param elem an object.
  316.   * @return <code>true</code> if and only if the specified object
  317.   * is the same as a component in this LinkedList, as determined by the
  318.   * <tt>equals</tt> method; <code>false</code> otherwise.
  319.   */
  320. public boolean contains(Object elem) {
  321. return indexOf(elem, 0) >= 0;
  322. }
  323.  
  324. /**
  325.   * Searches for the first occurence of the given argument, testing
  326.   * for equality using the <code>equals</code> method.
  327.   *
  328.   * @param elem an object.
  329.   * @return the index of the first occurrence of the argument in this
  330.   * LinkedList, that is, the smallest value <tt>k</tt> such that
  331.   * <tt>elem.equals(elementData[k])</tt> is <tt>true</tt>;
  332.   * returns <code>-1</code> if the object is not found.
  333.   * @see Object#equals(Object)
  334.   */
  335. public int indexOf(Object elem) {
  336. return indexOf(elem, 0);
  337. }
  338.  
  339. /**
  340.   * Searches for the first occurence of the given argument, beginning
  341.   * the search at <code>index</code>, and testing for equality using
  342.   * the <code>equals</code> method.
  343.   *
  344.   * @param elem an object.
  345.   * @param index the non-negative index to start searching from.
  346.   * @return the index of the first occurrence of the object argument in
  347.   * this LinkedList at position <code>index</code> or later in the
  348.   * LinkedList, that is, the smallest value <tt>k</tt> such that
  349.   * <tt>elem.equals(elementData[k]) && (k &gt;= index)</tt> is
  350.   * <tt>true</tt>; returns <code>-1</code> if the object is not
  351.   * found. (Returns <code>-1</code> if <tt>index</tt> &gt;= the
  352.   * current size of this <tt>LinkedList</tt>.)
  353.   * @exception IndexOutOfBoundsException if <tt>index</tt> is negative.
  354.   * @see Object#equals(Object)
  355.   */
  356. public synchronized int indexOf(Object elem, int index) {
  357. if (elem == null) {
  358. for (int i = index ; i < elementCount ; i++)
  359. if (elementData[i]==null)
  360. return i;
  361. } else {
  362. for (int i = index ; i < elementCount ; i++)
  363. if (elem.equals(elementData[i]))
  364. return i;
  365. }
  366. return -1;
  367. }
  368.  
  369. /**
  370.   * Returns the index of the last occurrence of the specified object in
  371.   * this LinkedList.
  372.   *
  373.   * @param elem the desired component.
  374.   * @return the index of the last occurrence of the specified object in
  375.   * this LinkedList, that is, the largest value <tt>k</tt> such that
  376.   * <tt>elem.equals(elementData[k])</tt> is <tt>true</tt>;
  377.   * returns <code>-1</code> if the object is not found.
  378.   */
  379. public synchronized int lastIndexOf(Object elem) {
  380. return lastIndexOf(elem, elementCount-1);
  381. }
  382.  
  383. /**
  384.   * Searches backwards for the specified object, starting from the
  385.   * specified index, and returns an index to it.
  386.   *
  387.   * @param elem the desired component.
  388.   * @param index the index to start searching from.
  389.   * @return the index of the last occurrence of the specified object in this
  390.   * LinkedList at position less than or equal to <code>index</code> in
  391.   * the LinkedList, that is, the largest value <tt>k</tt> such that
  392.   * <tt>elem.equals(elementData[k]) && (k &lt;= index)</tt> is
  393.   * <tt>true</tt>; <code>-1</code> if the object is not found.
  394.   * (Returns <code>-1</code> if <tt>index</tt> is negative.)
  395.   * @exception IndexOutOfBoundsException if <tt>index</tt> is greater
  396.   * than or equal to the current size of this LinkedList.
  397.   */
  398. public synchronized int lastIndexOf(Object elem, int index) {
  399. if (index >= elementCount)
  400. throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
  401.  
  402. if (elem == null) {
  403. for (int i = index; i >= 0; i--)
  404. if (elementData[i]==null)
  405. return i;
  406. } else {
  407. for (int i = index; i >= 0; i--)
  408. if (elem.equals(elementData[i]))
  409. return i;
  410. }
  411. return -1;
  412. }
  413.  
  414. /**
  415.   * Returns the component at the specified index.<p>
  416.   *
  417.   * This method is identical in functionality to the get method
  418.   * (which is part of the List interface).
  419.   *
  420.   * @param index an index into this LinkedList.
  421.   * @return the component at the specified index.
  422.   * @exception ArrayIndexOutOfBoundsException if the <tt>index</tt>
  423.   * is negative or not less than the current size of this
  424.   * <tt>LinkedList</tt> object.
  425.   * given.
  426.   * @see #get(int)
  427.   * @see List
  428.   */
  429. public synchronized E elementAt(int index) {
  430. if (index >= elementCount) {
  431. throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
  432. }
  433.  
  434. return (E)elementData[index];
  435. }
  436.  
  437. /**
  438.   * Returns the first component (the item at index <tt>0</tt>) of
  439.   * this LinkedList.
  440.   *
  441.   * @return the first component of this LinkedList.
  442.   * @exception NoSuchElementException if this LinkedList has no components.
  443.   */
  444. public synchronized E firstElement() {
  445. if (elementCount == 0) {
  446. throw new NoSuchElementException();
  447. }
  448. return (E)elementData[0];
  449. }
  450.  
  451. /**
  452.   * Returns the last component of the LinkedList.
  453.   *
  454.   * @return the last component of the LinkedList, i.e., the component at index
  455.   * <code>size()&nbsp;-&nbsp;1</code>.
  456.   * @exception NoSuchElementException if this LinkedList is empty.
  457.   */
  458. public synchronized E lastElement() {
  459. if (elementCount == 0) {
  460. throw new NoSuchElementException();
  461. }
  462. return (E)elementData[elementCount - 1];
  463. }
  464.  
  465. /**
  466.   * Sets the component at the specified <code>index</code> of this
  467.   * LinkedList to be the specified object. The previous component at that
  468.   * position is discarded.<p>
  469.   *
  470.   * The index must be a value greater than or equal to <code>0</code>
  471.   * and less than the current size of the LinkedList. <p>
  472.   *
  473.   * This method is identical in functionality to the set method
  474.   * (which is part of the List interface). Note that the set method reverses
  475.   * the order of the parameters, to more closely match array usage. Note
  476.   * also that the set method returns the old value that was stored at the
  477.   * specified position.
  478.   *
  479.   * @param obj what the component is to be set to.
  480.   * @param index the specified index.
  481.   * @exception ArrayIndexOutOfBoundsException if the index was invalid.
  482.   * @see #size()
  483.   * @see List
  484.   * @see #set(int, java.lang.Object)
  485.   */
  486. public synchronized void setElementAt(E obj, int index) {
  487. if (index >= elementCount) {
  488. throw new ArrayIndexOutOfBoundsException(index + " >= " +
  489. elementCount);
  490. }
  491. elementData[index] = obj;
  492. }
  493.  
  494. /**
  495.   * Deletes the component at the specified index. Each component in
  496.   * this LinkedList with an index greater or equal to the specified
  497.   * <code>index</code> is shifted downward to have an index one
  498.   * smaller than the value it had previously. The size of this LinkedList
  499.   * is decreased by <tt>1</tt>.<p>
  500.   *
  501.   * The index must be a value greater than or equal to <code>0</code>
  502.   * and less than the current size of the LinkedList. <p>
  503.   *
  504.   * This method is identical in functionality to the remove method
  505.   * (which is part of the List interface). Note that the remove method
  506.   * returns the old value that was stored at the specified position.
  507.   *
  508.   * @param index the index of the object to remove.
  509.   * @exception ArrayIndexOutOfBoundsException if the index was invalid.
  510.   * @see #size()
  511.   * @see #remove(int)
  512.   * @see List
  513.   */
  514. public synchronized void removeElementAt(int index) {
  515. modCount++;
  516. if (index >= elementCount) {
  517. throw new ArrayIndexOutOfBoundsException(index + " >= " +
  518. elementCount);
  519. }
  520. else if (index < 0) {
  521. throw new ArrayIndexOutOfBoundsException(index);
  522. }
  523. int j = elementCount - index - 1;
  524. if (j > 0) {
  525. System.arraycopy(elementData, index + 1, elementData, index, j);
  526. }
  527. elementCount--;
  528. elementData[elementCount] = null; /* to let gc do its work */
  529. }
  530.  
  531. /**
  532.   * Inserts the specified object as a component in this LinkedList at the
  533.   * specified <code>index</code>. Each component in this LinkedList with
  534.   * an index greater or equal to the specified <code>index</code> is
  535.   * shifted upward to have an index one greater than the value it had
  536.   * previously. <p>
  537.   *
  538.   * The index must be a value greater than or equal to <code>0</code>
  539.   * and less than or equal to the current size of the LinkedList. (If the
  540.   * index is equal to the current size of the LinkedList, the new element
  541.   * is appended to the LinkedList.)<p>
  542.   *
  543.   * This method is identical in functionality to the add(Object, int) method
  544.   * (which is part of the List interface). Note that the add method reverses
  545.   * the order of the parameters, to more closely match array usage.
  546.   *
  547.   * @param obj the component to insert.
  548.   * @param index where to insert the new component.
  549.   * @exception ArrayIndexOutOfBoundsException if the index was invalid.
  550.   * @see #size()
  551.   * @see #add(int, Object)
  552.   * @see List
  553.   */
  554. public synchronized void insertElementAt(E obj, int index) {
  555. modCount++;
  556. if (index > elementCount) {
  557. throw new ArrayIndexOutOfBoundsException(index
  558. + " > " + elementCount);
  559. }
  560. ensureCapacityHelper(elementCount + 1);
  561. System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
  562. elementData[index] = obj;
  563. elementCount++;
  564. }
  565.  
  566. /**
  567.   * Adds the specified component to the end of this LinkedList,
  568.   * increasing its size by one. The capacity of this LinkedList is
  569.   * increased if its size becomes greater than its capacity. <p>
  570.   *
  571.   * This method is identical in functionality to the add(Object) method
  572.   * (which is part of the List interface).
  573.   *
  574.   * @param obj the component to be added.
  575.   * @see #add(Object)
  576.   * @see List
  577.   */
  578. public synchronized void addElement(E obj) {
  579. modCount++;
  580. ensureCapacityHelper(elementCount + 1);
  581. elementData[elementCount++] = obj;
  582. }
  583.  
  584. /**
  585.   * Removes the first (lowest-indexed) occurrence of the argument
  586.   * from this LinkedList. If the object is found in this LinkedList, each
  587.   * component in the LinkedList with an index greater or equal to the
  588.   * object's index is shifted downward to have an index one smaller
  589.   * than the value it had previously.<p>
  590.   *
  591.   * This method is identical in functionality to the remove(Object)
  592.   * method (which is part of the List interface).
  593.   *
  594.   * @param obj the component to be removed.
  595.   * @return <code>true</code> if the argument was a component of this
  596.   * LinkedList; <code>false</code> otherwise.
  597.   * @see List#remove(Object)
  598.   * @see List
  599.   */
  600. public synchronized boolean removeElement(Object obj) {
  601. modCount++;
  602. int i = indexOf(obj);
  603. if (i >= 0) {
  604. removeElementAt(i);
  605. return true;
  606. }
  607. return false;
  608. }
  609.  
  610. /**
  611.   * Removes all components from this LinkedList and sets its size to zero.<p>
  612.   *
  613.   * This method is identical in functionality to the clear method
  614.   * (which is part of the List interface).
  615.   *
  616.   * @see #clear
  617.   * @see List
  618.   */
  619. public synchronized void removeAllElements() {
  620. modCount++;
  621. // Let gc do its work
  622. for (int i = 0; i < elementCount; i++)
  623. elementData[i] = null;
  624.  
  625. elementCount = 0;
  626. }
  627.  
  628. /**
  629.   * Returns a clone of this LinkedList. The copy will contain a
  630.   * reference to a clone of the internal data array, not a reference
  631.   * to the original internal data array of this <tt>LinkedList</tt> object.
  632.   *
  633.   * @return a clone of this LinkedList.
  634.   */
  635. public synchronized Object clone() {
  636. try {
  637. LinkedList<E> v = (LinkedList<E>) super.clone();
  638. v.elementData = new Object[elementCount];
  639. System.arraycopy(elementData, 0, v.elementData, 0, elementCount);
  640. v.modCount = 0;
  641. return v;
  642. } catch (CloneNotSupportedException e) {
  643. // this shouldn't happen, since we are Cloneable
  644. throw new InternalError();
  645. }
  646. }
  647.  
  648. /**
  649.   * Returns an array containing all of the elements in this LinkedList
  650.   * in the correct order.
  651.   *
  652.   * @since 1.2
  653.   */
  654. public synchronized Object[] toArray() {
  655. Object[] result = new Object[elementCount];
  656. System.arraycopy(elementData, 0, result, 0, elementCount);
  657. return result;
  658. }
  659.  
  660. /**
  661.   * Returns an array containing all of the elements in this LinkedList in the
  662.   * correct order; the runtime type of the returned array is that of the
  663.   * specified array. If the LinkedList fits in the specified array, it is
  664.   * returned therein. Otherwise, a new array is allocated with the runtime
  665.   * type of the specified array and the size of this LinkedList.<p>
  666.   *
  667.   * If the LinkedList fits in the specified array with room to spare
  668.   * (i.e., the array has more elements than the LinkedList),
  669.   * the element in the array immediately following the end of the
  670.   * LinkedList is set to null. This is useful in determining the length
  671.   * of the LinkedList <em>only</em> if the caller knows that the LinkedList
  672.   * does not contain any null elements.
  673.   *
  674.   * @param a the array into which the elements of the LinkedList are to
  675.   * be stored, if it is big enough; otherwise, a new array of the
  676.   * same runtime type is allocated for this purpose.
  677.   * @return an array containing the elements of the LinkedList.
  678.   * @exception ArrayStoreException the runtime type of a is not a supertype
  679.   * of the runtime type of every element in this LinkedList.
  680.   * @throws NullPointerException if the given array is null.
  681.   * @since 1.2
  682.   */
  683. public synchronized <T> T[] toArray(T[] a) {
  684. if (a.length < elementCount)
  685. a = (T[])java.lang.reflect.Array.newInstance(
  686. a.getClass().getComponentType(), elementCount);
  687.  
  688. System.arraycopy(elementData, 0, a, 0, elementCount);
  689.  
  690. if (a.length > elementCount)
  691. a[elementCount] = null;
  692.  
  693. return a;
  694. }
  695.  
  696. // Positional Access Operations
  697.  
  698. /**
  699.   * Returns the element at the specified position in this LinkedList.
  700.   *
  701.   * @param index index of element to return.
  702.   * @return object at the specified index
  703.   * @exception ArrayIndexOutOfBoundsException index is out of range (index
  704.   * &lt; 0 || index &gt;= size()).
  705.   * @since 1.2
  706.   */
  707. public synchronized E get(int index) {
  708. if (index >= elementCount)
  709. throw new ArrayIndexOutOfBoundsException(index);
  710.  
  711. return (E)elementData[index];
  712. }
  713.  
  714. /**
  715.   * Replaces the element at the specified position in this LinkedList with the
  716.   * specified element.
  717.   *
  718.   * @param index index of element to replace.
  719.   * @param element element to be stored at the specified position.
  720.   * @return the element previously at the specified position.
  721.   * @exception ArrayIndexOutOfBoundsException index out of range
  722.   * (index &lt; 0 || index &gt;= size()).
  723.   * @since 1.2
  724.   */
  725. public synchronized E set(int index, E element) {
  726. if (index >= elementCount)
  727. throw new ArrayIndexOutOfBoundsException(index);
  728.  
  729. Object oldValue = elementData[index];
  730. elementData[index] = element;
  731. return (E)oldValue;
  732. }
  733.  
  734. /**
  735.   * Appends the specified element to the end of this LinkedList.
  736.   *
  737.   * @param o element to be appended to this LinkedList.
  738.   * @return true (as per the general contract of Collection.add).
  739.   * @since 1.2
  740.   */
  741. public synchronized boolean add(E o) {
  742. modCount++;
  743. ensureCapacityHelper(elementCount + 1);
  744. elementData[elementCount++] = o;
  745. return true;
  746. }
  747.  
  748. /**
  749.   * Removes the first occurrence of the specified element in this LinkedList
  750.   * If the LinkedList does not contain the element, it is unchanged. More
  751.   * formally, removes the element with the lowest index i such that
  752.   * <code>(o==null ? get(i)==null : o.equals(get(i)))</code> (if such
  753.   * an element exists).
  754.   *
  755.   * @param o element to be removed from this LinkedList, if present.
  756.   * @return true if the LinkedList contained the specified element.
  757.   * @since 1.2
  758.   */
  759. public boolean remove(Object o) {
  760. return removeElement(o);
  761. }
  762.  
  763. /**
  764.   * Inserts the specified element at the specified position in this LinkedList.
  765.   * Shifts the element currently at that position (if any) and any
  766.   * subsequent elements to the right (adds one to their indices).
  767.   *
  768.   * @param index index at which the specified element is to be inserted.
  769.   * @param element element to be inserted.
  770.   * @exception ArrayIndexOutOfBoundsException index is out of range
  771.   * (index &lt; 0 || index &gt; size()).
  772.   * @since 1.2
  773.   */
  774. public void add(int index, E element) {
  775. insertElementAt(element, index);
  776. }
  777.  
  778. /**
  779.   * Removes the element at the specified position in this LinkedList.
  780.   * shifts any subsequent elements to the left (subtracts one from their
  781.   * indices). Returns the element that was removed from the LinkedList.
  782.   *
  783.   * @exception ArrayIndexOutOfBoundsException index out of range (index
  784.   * &lt; 0 || index &gt;= size()).
  785.   * @param index the index of the element to removed.
  786.   * @return element that was removed
  787.   * @since 1.2
  788.   */
  789. public synchronized E remove(int index) {
  790. modCount++;
  791. if (index >= elementCount)
  792. throw new ArrayIndexOutOfBoundsException(index);
  793. Object oldValue = elementData[index];
  794.  
  795. int numMoved = elementCount - index - 1;
  796. if (numMoved > 0)
  797. System.arraycopy(elementData, index+1, elementData, index,
  798. numMoved);
  799. elementData[--elementCount] = null; // Let gc do its work
  800.  
  801. return (E)oldValue;
  802. }
  803.  
  804. /**
  805.   * Removes all of the elements from this LinkedList. The LinkedList will
  806.   * be empty after this call returns (unless it throws an exception).
  807.   *
  808.   * @since 1.2
  809.   */
  810. public void clear() {
  811. removeAllElements();
  812. }
  813.  
  814. // Bulk Operations
  815.  
  816. /**
  817.   * Returns true if this LinkedList contains all of the elements in the
  818.   * specified Collection.
  819.   *
  820.   * @param c a collection whose elements will be tested for containment
  821.   * in this LinkedList
  822.   * @return true if this LinkedList contains all of the elements in the
  823.   * specified collection.
  824.   * @throws NullPointerException if the specified collection is null.
  825.   */
  826. public synchronized boolean containsAll(Collection<?> c) {
  827. return super.containsAll(c);
  828. }
  829.  
  830. /**
  831.   * Appends all of the elements in the specified Collection to the end of
  832.   * this LinkedList, in the order that they are returned by the specified
  833.   * Collection's Iterator. The behavior of this operation is undefined if
  834.   * the specified Collection is modified while the operation is in progress.
  835.   * (This implies that the behavior of this call is undefined if the
  836.   * specified Collection is this LinkedList, and this LinkedList is nonempty.)
  837.   *
  838.   * @param c elements to be inserted into this LinkedList.
  839.   * @return <tt>true</tt> if this LinkedList changed as a result of the call.
  840.   * @throws NullPointerException if the specified collection is null.
  841.   * @since 1.2
  842.   */
  843. public synchronized boolean addAll(Collection<? extends E> c) {
  844. modCount++;
  845. Object[] a = c.toArray();
  846. int numNew = a.length;
  847. ensureCapacityHelper(elementCount + numNew);
  848. System.arraycopy(a, 0, elementData, elementCount, numNew);
  849. elementCount += numNew;
  850. return numNew != 0;
  851. }
  852.  
  853. /**
  854.   * Removes from this LinkedList all of its elements that are contained in the
  855.   * specified Collection.
  856.   *
  857.   * @param c a collection of elements to be removed from the LinkedList
  858.   * @return true if this LinkedList changed as a result of the call.
  859.   * @throws NullPointerException if the specified collection is null.
  860.   * @since 1.2
  861.   */
  862. public synchronized boolean removeAll(Collection<?> c) {
  863. return super.removeAll(c);
  864. }
  865.  
  866. /**
  867.   * Retains only the elements in this LinkedList that are contained in the
  868.   * specified Collection. In other words, removes from this LinkedList all
  869.   * of its elements that are not contained in the specified Collection.
  870.   *
  871.   * @param c a collection of elements to be retained in this LinkedList
  872.   * (all other elements are removed)
  873.   * @return true if this LinkedList changed as a result of the call.
  874.   * @throws NullPointerException if the specified collection is null.
  875.   * @since 1.2
  876.   */
  877. public synchronized boolean retainAll(Collection<?> c) {
  878. return super.retainAll(c);
  879. }
  880.  
  881. /**
  882.   * Inserts all of the elements in the specified Collection into this
  883.   * LinkedList at the specified position. Shifts the element currently at
  884.   * that position (if any) and any subsequent elements to the right
  885.   * (increases their indices). The new elements will appear in the LinkedList
  886.   * in the order that they are returned by the specified Collection's
  887.   * iterator.
  888.   *
  889.   * @param index index at which to insert first element
  890.   * from the specified collection.
  891.   * @param c elements to be inserted into this LinkedList.
  892.   * @return <tt>true</tt> if this LinkedList changed as a result of the call.
  893.   * @exception ArrayIndexOutOfBoundsException index out of range (index
  894.   * &lt; 0 || index &gt; size()).
  895.   * @throws NullPointerException if the specified collection is null.
  896.   * @since 1.2
  897.   */
  898. public synchronized boolean addAll(int index, Collection<? extends E> c) {
  899. modCount++;
  900. if (index < 0 || index > elementCount)
  901. throw new ArrayIndexOutOfBoundsException(index);
  902.  
  903. Object[] a = c.toArray();
  904. int numNew = a.length;
  905. ensureCapacityHelper(elementCount + numNew);
  906.  
  907. int numMoved = elementCount - index;
  908. if (numMoved > 0)
  909. System.arraycopy(elementData, index, elementData, index + numNew,
  910. numMoved);
  911.  
  912. System.arraycopy(a, 0, elementData, index, numNew);
  913. elementCount += numNew;
  914. return numNew != 0;
  915. }
  916.  
  917. /**
  918.   * Compares the specified Object with this LinkedList for equality. Returns
  919.   * true if and only if the specified Object is also a List, both Lists
  920.   * have the same size, and all corresponding pairs of elements in the two
  921.   * Lists are <em>equal</em>. (Two elements <code>e1</code> and
  922.   * <code>e2</code> are <em>equal</em> if <code>(e1==null ? e2==null :
  923.   * e1.equals(e2))</code>.) In other words, two Lists are defined to be
  924.   * equal if they contain the same elements in the same order.
  925.   *
  926.   * @param o the Object to be compared for equality with this LinkedList.
  927.   * @return true if the specified Object is equal to this LinkedList
  928.   */
  929. public synchronized boolean equals(Object o) {
  930. return super.equals(o);
  931. }
  932.  
  933. /**
  934.   * Returns the hash code value for this LinkedList.
  935.   */
  936. public synchronized int hashCode() {
  937. return super.hashCode();
  938. }
  939.  
  940. /**
  941.   * Returns a string representation of this LinkedList, containing
  942.   * the String representation of each element.
  943.   */
  944. public synchronized String toString() {
  945. return super.toString();
  946. }
  947.  
  948. /**
  949.   * Returns a view of the portion of this List between fromIndex,
  950.   * inclusive, and toIndex, exclusive. (If fromIndex and ToIndex are
  951.   * equal, the returned List is empty.) The returned List is backed by this
  952.   * List, so changes in the returned List are reflected in this List, and
  953.   * vice-versa. The returned List supports all of the optional List
  954.   * operations supported by this List.<p>
  955.   *
  956.   * This method eliminates the need for explicit range operations (of
  957.   * the sort that commonly exist for arrays). Any operation that expects
  958.   * a List can be used as a range operation by operating on a subList view
  959.   * instead of a whole List. For example, the following idiom
  960.   * removes a range of elements from a List:
  961.   * <pre>
  962.   * list.subList(from, to).clear();
  963.   * </pre>
  964.   * Similar idioms may be constructed for indexOf and lastIndexOf,
  965.   * and all of the algorithms in the Collections class can be applied to
  966.   * a subList.<p>
  967.   *
  968.   * The semantics of the List returned by this method become undefined if
  969.   * the backing list (i.e., this List) is <i>structurally modified</i> in
  970.   * any way other than via the returned List. (Structural modifications are
  971.   * those that change the size of the List, or otherwise perturb it in such
  972.   * a fashion that iterations in progress may yield incorrect results.)
  973.   *
  974.   * @param fromIndex low endpoint (inclusive) of the subList.
  975.   * @param toIndex high endpoint (exclusive) of the subList.
  976.   * @return a view of the specified range within this List.
  977.   * @throws IndexOutOfBoundsException endpoint index value out of range
  978.   * <code>(fromIndex &lt; 0 || toIndex &gt; size)</code>
  979.   * @throws IllegalArgumentException endpoint indices out of order
  980.   * <code>(fromIndex &gt; toIndex)</code>
  981.   */
  982. public synchronized List<E> subList(int fromIndex, int toIndex) {
  983. return Collections.synchronizedList(super.subList(fromIndex, toIndex),
  984. this);
  985. }
  986.  
  987. /**
  988.   * Removes from this List all of the elements whose index is between
  989.   * fromIndex, inclusive and toIndex, exclusive. Shifts any succeeding
  990.   * elements to the left (reduces their index).
  991.   * This call shortens the ArrayList by (toIndex - fromIndex) elements. (If
  992.   * toIndex==fromIndex, this operation has no effect.)
  993.   *
  994.   * @param fromIndex index of first element to be removed.
  995.   * @param toIndex index after last element to be removed.
  996.   */
  997. protected synchronized void removeRange(int fromIndex, int toIndex) {
  998. modCount++;
  999. int numMoved = elementCount - toIndex;
  1000. System.arraycopy(elementData, toIndex, elementData, fromIndex,
  1001. numMoved);
  1002.  
  1003. // Let gc do its work
  1004. int newElementCount = elementCount - (toIndex-fromIndex);
  1005. while (elementCount != newElementCount)
  1006. elementData[--elementCount] = null;
  1007. }
  1008.  
  1009. /**
  1010.   * Save the state of the <tt>LinkedList</tt> instance to a stream (that
  1011.   * is, serialize it). This method is present merely for synchronization.
  1012.   * It just calls the default readObject method.
  1013.   */
  1014. private synchronized void writeObject(java.io.ObjectOutputStream s)
  1015. throws java.io.IOException
  1016. {
  1017. s.defaultWriteObject();
  1018. }
  1019. }

  1. /**
  2.  *
  3.  * @author Philip Kao
  4.  */
  5.  
  6. import java.io.*;
  7. import java.util.*;
  8. import javax.swing.*;
  9. import java.awt.*;
  10.  
  11. public class OrderList extends LinkedList<TreeData>
  12. {
  13. public static final int SORT_BY_MODEL_NO = 0;
  14. public static final int SORT_BY_THICKNESS = 1;
  15. public static final int SORT_BY_WIDTH = 2;
  16. public static final int SORT_BY_COLOR = 3;
  17.  
  18. // Constructor
  19. public OrderList()
  20. {
  21. super(); // accomodate 5 items, extend by 5 when overflow
  22. }
  23.  
  24. /**
  25.   * Constructor with stuff
  26.   * @param file
  27.   */
  28. public OrderList(File inFile, Component c)
  29. {
  30. try
  31. {
  32. Scanner in = new Scanner(inFile);
  33. while (in.hasNextLine())
  34. {
  35. Scanner lineScanner = new Scanner(in.nextLine());
  36. lineScanner.useDelimiter("\t");
  37. try {
  38. String model = lineScanner.next();
  39. int quantity = lineScanner.nextInt();
  40. double thickness = lineScanner.nextDouble();
  41. double width = lineScanner.nextDouble();
  42. String color = lineScanner.next();
  43. double plys = lineScanner.nextDouble();
  44.  
  45. add(new TreeData(model, quantity, thickness, width, color, plys));
  46. }
  47. catch (NoSuchElementException e) { continue; }
  48. }
  49. }
  50. catch (IOException e)
  51. { JOptionPane.showMessageDialog(c, "Error Opening File",
  52. "Error", JOptionPane.ERROR_MESSAGE ); }
  53. }
  54.  
  55. //add item to order list; if item of same specs exists, add to quantity
  56. public boolean add(TreeData item)
  57. {
  58. for (int i = 0; i < size(); i++) {
  59. TreeData temp = get(i);
  60. if (temp.equals(item)) {
  61. temp.setQuantity(temp.getQuantity() + item.getQuantity());
  62. return true;
  63. }
  64. }
  65. return super.add(item);
  66. }
  67.  
  68. /**
  69.   *
  70.   * @param sortType
  71.   */
  72. public void sort(int sortType)
  73. {
  74. quicksort(0, size()-1, sortType);
  75. }
  76.  
  77. /**
  78.   * Sort an array using Quicksort algorithm. Adapted from method in C at
  79.   * http://www.tcnj.edu/~mmmartin/CMSC410/qs-complexity.doc
  80.   * @param a An array of Comparable items.
  81.   * @param left Start point of range.
  82.   * @param right End point of range.
  83.   */
  84. private void quicksort(int left, int right, int sortType)
  85. {
  86. if (left >= right) return;
  87. else
  88. {
  89. int l = left;
  90. int r = right;
  91. TreeData pivot = get((l+r)/2); // choose pivot as middle item
  92. // partition
  93. do
  94. {
  95. while (compare(get(l),pivot,sortType) < 0) l++;
  96. while (compare(get(r),pivot,sortType) > 0) r--;
  97. if (l <= r)
  98. {
  99. // swap a[l] and a[r]
  100. TreeData tmp = get(l);
  101. set(l, get(r));
  102. set(r, tmp);
  103. // move on
  104. l++;
  105. r--;
  106. }
  107. }
  108. while (l <= r);
  109.  
  110. // recursively sort left and right partitions
  111. quicksort(left, r, sortType);
  112. quicksort(l, right, sortType);
  113. }
  114. }
  115.  
  116. /**
  117.   * @param a First object of field type to compare
  118.   * @param b Second object of field type to compare
  119.   * @param sortType Identifier for field type
  120.   */
  121. private int compare(TreeData a, TreeData b, int sortType)
  122. {
  123. String s1, s2;
  124. double d1, d2;
  125.  
  126. // Sorts by model number or color (string type)
  127. switch (sortType)
  128. {
  129. case SORT_BY_MODEL_NO:
  130. s1 = a.getModelNo();
  131. s2 = b.getModelNo();
  132. // If s1 is <= s2, returns true
  133. return s1.compareTo(s2);
  134. case SORT_BY_COLOR:
  135. s1 = a.getColor();
  136. s2 = b.getColor();
  137. // If s1 is <= s2, returns true
  138. return s1.compareTo(s2);
  139. case SORT_BY_THICKNESS:
  140. // Class compare
  141. d1 = a.getThickness();
  142. d2 = b.getThickness();
  143. return Double.compare(d1,d2);
  144. case SORT_BY_WIDTH:
  145. // Class compare
  146. d1 = a.getWidth();
  147. d2 = b.getWidth();
  148. return Double.compare(d1,d2);
  149. }
  150. return 0;
  151. }
  152.  
  153. /**
  154.   *
  155.   */
  156. public String toString()
  157. {
  158. String listOutput = "";
  159. for (int i = 0; i < size(); i++)
  160. {
  161. TreeData item = get(i);
  162. if (item == null) break;
  163. listOutput += item.toString() + "\r\n";
  164. }
  165. return listOutput;
  166. }
  167.  
  168. /**
  169.   *
  170.   */
  171. public static void main(String[] args)
  172. {
  173. OrderList list = new OrderList();
  174. list.sort(SORT_BY_WIDTH);
  175. for (int i = 0; i<5; i++)
  176. System.out.println(list.get(i).toString());
  177. }
  178. }

the copied vector class is LinkedList.java and it doesn't work. anyone know why.
it points to the OrderList...
Reply With Quote Quick reply to this message  
Join Date: Mar 2005
Posts: 13
Reputation: buggytoast is an unknown quantity at this point 
Solved Threads: 0
buggytoast buggytoast is offline Offline
Newbie Poster

Re: Source Code that don't work?

 
0
  #2
Apr 2nd, 2006
Sorry for double posting. I'm just going to give a more in depth thing explanation of what I said before.

1. My program works fine now. In Orderlist i originally wrote
public class OrderList extends Vector<TreeData>
However using vectors doesn't show me using mastery. I need to have the code for the vectors and just change the variables and such. What I did was I took the source code of vectors and created a new class called "LinkedList".

So I replaced extends Vector<TreeData> with extends LinkedList and it doesn't work anymore. I changed the variables around but still. no can do

I hope that cleared things up abit. Thanks for your time.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Java Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC