List vs HashSet

Hi,
I currently have a code working with a list that acts as a set (before every add I check contains), the rqeuirements from this set is pretty much all in all, it gets inserted into frequently, removed from frequently and iterated on frequently. This set is
the value in a hashtable which contains many similar lists, some are extremely small (1-4 items in the set) to very big (100000+). I am currently facing a problem with removing items from the set, on larger sets due to the amount of items the contains
takes a long time and gives a very bad performance result.
I am considering changing to HashSet, I know of the quite large memory overhead i'll be getting which is unfortunate and while I am limited due to older machines, it is a overhead i'm willilng to accept. I looked into lowering the memory footprint of HashSet
and didn't find any way to do so. I also made some performance checks and saw i'll be getting a overhead in insert (about 130% of the current input) and in the iteration a small overhead (less than 10%), the delete performance however increases by a huge percent
(delete from about a 100000 set which took around 3500ms now takes 13ms). Now after all this my actual question, is there any other parameter I should be expecting to see changed? have I missed something in the memory overhead, is there a way to lower it?
Do you recommend any other data type for my use?
Thanks!
Gil

I would use a Dictionary instead of a Hash.  The key in the dictionary uses a built in hash function.  You can add a dictionary to your list very easily with Linq.  The dictionary value is a pointer to the list.  So the addional overhead
for the Dictionary is the number of items in the List * (size of key + size of pointer to value).
jdweng

Similar Messages

  • Help with my CheckboxJlist

    ok I am trying to get a list with checkboxes in it. I am playing with an axample given in the Swing Hacks book. t is all working for me execpt that when I click on a single item if no other item is selected you cannot click that same item agan to unselect it(you have to click on another item). Anyone see a good way to fix this here is the class below
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    public class CheckBoxJList extends JList
        implements ListSelectionListener {
        static Color listForeground, listBackground,
            listSelectionForeground,
            listSelectionBackground;
        static {
            UIDefaults uid = UIManager.getLookAndFeel().getDefaults();
            listForeground =  uid.getColor ("List.foreground");
            listBackground =  uid.getColor ("List.background");
            listSelectionForeground =  uid.getColor ("List.selectionForeground");
            listSelectionBackground =  uid.getColor ("List.selectionBackground");
        HashSet selectionCache = new HashSet();
        int toggleIndex = -1;
        boolean toggleWasSelected;
        public CheckBoxJList() {
            super();
            setCellRenderer (new CheckBoxListCellRenderer());
            addListSelectionListener (this);
        // ListSelectionListener implementation
        public void valueChanged (ListSelectionEvent lse) {
            System.out.println (lse);
            if (! lse.getValueIsAdjusting()) {
                removeListSelectionListener (this);
                // remember everything selected as a result of this action
                HashSet newSelections = new HashSet();
                int size = getModel().getSize();
                for (int i=0; i<size; i++) {
                    if (getSelectionModel().isSelectedIndex(i)) {
                        newSelections.add (new Integer(i));
                // turn on everything that was previously selected
                Iterator it = selectionCache.iterator();
                while (it.hasNext()) {
                    int index = ((Integer) it.next()).intValue();
                    System.out.println ("adding " + index);
                    getSelectionModel().addSelectionInterval(index, index);
                // add or remove the delta
                it = newSelections.iterator();
                while (it.hasNext()) {
                    Integer nextInt = (Integer) it.next();
                    int index = nextInt.intValue();
                    if (selectionCache.contains (nextInt))
                        getSelectionModel().removeSelectionInterval (index, index);
                    else
                        getSelectionModel().addSelectionInterval (index, index);
                // save selections for next time
                selectionCache.clear();
                for (int i=0; i<size; i++) {
                    if (getSelectionModel().isSelectedIndex(i)) {
                        System.out.println ("caching " + i);
                        selectionCache.add (new Integer(i));
                addListSelectionListener (this);
        public void popList (ArrayList<String> items) {
            DefaultListModel defModel = new DefaultListModel();
            for(int idx=0;items.size()>idx;idx++){
                 defModel.addElement(items.get(idx));
            this.setModel (defModel);
        class CheckBoxListCellRenderer extends JComponent
            implements ListCellRenderer {
            DefaultListCellRenderer defaultComp;
            JCheckBox checkbox;
            public CheckBoxListCellRenderer() {
                setLayout (new BorderLayout());
                defaultComp = new DefaultListCellRenderer();
                checkbox = new JCheckBox();
                add (checkbox, BorderLayout.WEST);
                add (defaultComp, BorderLayout.CENTER);
            public Component getListCellRendererComponent(JList list,
                                                          Object  value,
                                                          int index,
                                                          boolean isSelected,
                                                          boolean cellHasFocus){
                defaultComp.getListCellRendererComponent (list, value, index,
                                                          isSelected, cellHasFocus);
                checkbox.setSelected (isSelected);
                checkbox.setForeground (isSelected ?
                                        listSelectionForeground :
                                        listForeground);
                checkbox.setBackground (isSelected ?
                                        listSelectionBackground :
                                        listBackground);
                checkbox.setSelected (isSelected);
                Component[] comps = getComponents();
                for (int i=0; i<comps.length; i++) {
                    comps.setForeground (listForeground);
    comps[i].setBackground (listBackground);
    return this;
    public void valueChanged(){

    deiter wrote:
    I need help with my blackberry 9300 it keeps saying “Associating bbm with your blackberry I'd“ can someone help me plz and it also says it on my blackberry 9900
    Hi deiter
    Welcome to BlackBerry Support Forums
    Who is your Carrier and do you have BlackBerry Data Plan on your account from your Carrier ?
    Click " Like " if you want to Thank someone.
    If Problem Resolves mark the post(s) as " Solution ", so that other can make use of it.

  • Crawling the Web with Java

    Hi everyone.
    I've been trying to learn how to make a web crawler in java following this detailed albeit old tutorial: http://www.devarticles.com/c/a/Java/Crawling-the-Web-with-Java/
    The SearchCrawler class they feature can be found in two parts:
    First part: http://www.devarticles.com/c/a/Java/Crawling-the-Web-with-Java/3/
    Second part: http://www.devarticles.com/c/a/Java/Crawling-the-Web-with-Java/4/
    I don't want to copy and paste the code because it is really long and an eyesore if viewing here.
    I get a lot of errors when compiling of which I do not understand. The majority of the errors (62 of them to be precise) are "class, interface or enum expected" errors, with the remaining few being "illegal start of type" and "<identifier> expected" errors.
    Can someone here perhaps take a look at it and compile it and see if they also get the same errors? I realise it is an old tutorial but there are hardly any detailed resources I can find for java web crawlers.
    Thanks.

    Odd I can't seem to log into my account. Never mind.
    I have used java before, the problem here I suppose is I'm not good enough to spot what's the problem. The code seems fine bracket wise and it has really left me stumped.
    If someone code put it in their editor and attempt to compile and see if I'm not the only one that's having a problem.. that would be much appreciated.
    For your convenience... the code from the example I linked:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.regex.*;
    import javax.swing.*;
    import javax.swing.table.*;
    // The Search Web Crawler
    public class SearchCrawler extends JFrame
      // Max URLs drop-down values.
      private static final String[] MAX_URLS =
        {"50", "100", "500", "1000"};
      // Cache of robot disallow lists.
      private HashMap disallowListCache = new HashMap();
      // Search GUI controls.
      private JTextField startTextField;
      private JComboBox maxComboBox;
      private JCheckBox limitCheckBox;
      private JTextField logTextField;
      private JTextField searchTextField;
      private JCheckBox caseCheckBox;
      private JButton searchButton;
      // Search stats GUI controls.
      private JLabel crawlingLabel2;
      private JLabel crawledLabel2;
      private JLabel toCrawlLabel2;
      private JProgressBar progressBar;
      private JLabel matchesLabel2;
      // Table listing search matches.
      private JTable table;
      // Flag for whether or not crawling is underway.
      private boolean crawling;
      // Matches log file print writer.
      private PrintWriter logFileWriter;
      // Constructor for Search Web Crawler.
      public SearchCrawler()
        // Set application title.
        setTitle("Search Crawler");
        // Set window size.
        setSize(600, 600);
         // Handle window closing events.
        addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
           actionExit();
        // Set up File menu.
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File"); 
        fileMenu.setMnemonic(KeyEvent.VK_F);
        JMenuItem fileExitMenuItem = new JMenuItem("Exit",
          KeyEvent.VK_X);
        fileExitMenuItem.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) { 
            actionExit();
        fileMenu.add(fileExitMenuItem);
        menuBar.add(fileMenu);
        setJMenuBar(menuBar);
        // Set up search panel.
        JPanel searchPanel = new JPanel();
        GridBagConstraints constraints;
        GridBagLayout layout = new GridBagLayout();
        searchPanel.setLayout(layout);
        JLabel startLabel = new JLabel("Start URL:");
        constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.EAST; 
        constraints.insets = new Insets(5, 5, 0, 0);
        layout.setConstraints(startLabel, constraints);
        searchPanel.add(startLabel);
        startTextField = new JTextField();
        constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.insets = new Insets(5, 5, 0, 5);
        layout.setConstraints(startTextField, constraints);
        searchPanel.add(startTextField);
        JLabel maxLabel = new JLabel("Max URLs to Crawl:");
        constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(5, 5, 0, 0);
        layout.setConstraints(maxLabel, constraints);
        searchPanel.add(maxLabel);
        maxComboBox = new JComboBox(MAX_URLS);
        maxComboBox.setEditable(true);
        constraints = new GridBagConstraints();
        constraints.insets = new Insets(5, 5, 0, 0);
        layout.setConstraints(maxComboBox, constraints);
        searchPanel.add(maxComboBox);
        limitCheckBox =
          new JCheckBox("Limit crawling to Start URL site");
        constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.WEST;
        constraints.insets = new Insets(0, 10, 0, 0);
        layout.setConstraints(limitCheckBox, constraints);
        searchPanel.add(limitCheckBox);
        JLabel blankLabel = new JLabel();
        constraints = new GridBagConstraints();
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        layout.setConstraints(blankLabel, constraints);
        searchPanel.add(blankLabel);
        JLabel logLabel = new JLabel("Matches Log File:");
        constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(5, 5, 0, 0);
        layout.setConstraints(logLabel, constraints);
        searchPanel.add(logLabel);
        String file =
          System.getProperty("user.dir") +
          System.getProperty("file.separator") +
          "crawler.log";
        logTextField = new JTextField(file);
        constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.insets = new Insets(5, 5, 0, 5);
        layout.setConstraints(logTextField, constraints);
        searchPanel.add(logTextField);
        JLabel searchLabel = new JLabel("Search String:");
        constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.EAST; 
        constraints.insets = new Insets(5, 5, 0, 0);
        layout.setConstraints(searchLabel, constraints);
        searchPanel.add(searchLabel);
        searchTextField = new JTextField();
        constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.insets = new Insets(5, 5, 0, 0);
        constraints.gridwidth= 2;
        constraints.weightx = 1.0d;
        layout.setConstraints(searchTextField, constraints);
        searchPanel.add(searchTextField);
        caseCheckBox = new JCheckBox("Case Sensitive");
        constraints = new GridBagConstraints();
        constraints.insets = new Insets(5, 5, 0, 5);
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        layout.setConstraints(caseCheckBox, constraints);
        searchPanel.add(caseCheckBox);
        searchButton = new JButton("Search");
        searchButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            actionSearch();
        constraints = new GridBagConstraints();
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.insets = new Insets(5, 5, 5, 5);
        layout.setConstraints(searchButton, constraints);
        searchPanel.add(searchButton);
        JSeparator separator = new JSeparator();
        constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.insets = new Insets(5, 5, 5, 5);
        layout.setConstraints(separator, constraints);
        searchPanel.add(separator);
        JLabel crawlingLabel1 = new JLabel("Crawling:");
        constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(5, 5, 0, 0);
        layout.setConstraints(crawlingLabel1, constraints);
        searchPanel.add(crawlingLabel1);
        crawlingLabel2 = new JLabel();
        crawlingLabel2.setFont(
          crawlingLabel2.getFont().deriveFont(Font.PLAIN));
        constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.insets = new Insets(5, 5, 0, 5);
        layout.setConstraints(crawlingLabel2, constraints);
        searchPanel.add(crawlingLabel2);
        JLabel crawledLabel1 = new JLabel("Crawled URLs:");
        constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(5, 5, 0, 0);
        layout.setConstraints(crawledLabel1, constraints);
        searchPanel.add(crawledLabel1);
        crawledLabel2 = new JLabel();
        crawledLabel2.setFont(
          crawledLabel2.getFont().deriveFont(Font.PLAIN));
        constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.insets = new Insets(5, 5, 0, 5);
        layout.setConstraints(crawledLabel2, constraints);
        searchPanel.add(crawledLabel2);
        JLabel toCrawlLabel1 = new JLabel("URLs to Crawl:");
        constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(5, 5, 0, 0);
        layout.setConstraints(toCrawlLabel1, constraints);
        searchPanel.add(toCrawlLabel1);
        toCrawlLabel2 = new JLabel();
        toCrawlLabel2.setFont(
          toCrawlLabel2.getFont().deriveFont(Font.PLAIN));
        constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.insets = new Insets(5, 5, 0, 5);
        layout.setConstraints(toCrawlLabel2, constraints);
        searchPanel.add(toCrawlLabel2);
        JLabel progressLabel = new JLabel("Crawling Progress:");
        constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(5, 5, 0, 0);
        layout.setConstraints(progressLabel, constraints);
        searchPanel.add(progressLabel);
        progressBar = new JProgressBar();
        progressBar.setMinimum(0);
        progressBar.setStringPainted(true);
        constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.insets = new Insets(5, 5, 0, 5);
        layout.setConstraints(progressBar, constraints);
        searchPanel.add(progressBar);
        JLabel matchesLabel1 = new JLabel("Search Matches:");
        constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(5, 5, 10, 0);
        layout.setConstraints(matchesLabel1, constraints);
        searchPanel.add(matchesLabel1);
        matchesLabel2 = new JLabel();
        matchesLabel2.setFont(
          matchesLabel2.getFont().deriveFont(Font.PLAIN));
        constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.insets = new Insets(5, 5, 10, 5);
        layout.setConstraints(matchesLabel2, constraints);
        searchPanel.add(matchesLabel2);
        // Set up matches table.
        table =
          new JTable(new DefaultTableModel(new Object[][]{},
            new String[]{"URL"}) {
          public boolean isCellEditable(int row, int column)
            return false;
        // Set up Matches panel.
        JPanel matchesPanel = new JPanel();
        matchesPanel.setBorder(
          BorderFactory.createTitledBorder("Matches"));
        matchesPanel.setLayout(new BorderLayout());
        matchesPanel.add(new JScrollPane(table),
          BorderLayout.CENTER);
        // Add panels to display.
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(searchPanel, BorderLayout.NORTH);
        getContentPane().add(matchesPanel,BorderLayout.CENTER);
      // Exit this program.
      private void actionExit() {
        System.exit(0);
      // Handle Search/Stop button being clicked.
      private void actionSearch() {
        // If stop button clicked, turn crawling flag off.
        if (crawling) {
          crawling = false;
          return;
      ArrayList errorList = new ArrayList();
      // Validate that start URL has been entered.
      String startUrl = startTextField.getText().trim();
      if (startUrl.length() < 1) {
        errorList.add("Missing Start URL.");
      // Verify start URL.
      else if (verifyUrl(startUrl) == null) {
        errorList.add("Invalid Start URL.");
      // Validate that Max URLs is either empty or is a number.
      int maxUrls = 0;
      String max = ((String) maxComboBox.getSelectedItem()).trim();
      if (max.length() > 0) {
        try {
          maxUrls = Integer.parseInt(max);
        } catch (NumberFormatException e) {
        if (maxUrls < 1) {
          errorList.add("Invalid Max URLs value.");
      // Validate that matches log file has been entered.
      String logFile = logTextField.getText().trim();
      if (logFile.length() < 1) {
        errorList.add("Missing Matches Log File.");
      // Validate that search string has been entered.
      String searchString = searchTextField.getText().trim();
      if (searchString.length() < 1) {
        errorList.add("Missing Search String.");
      // Show errors, if any, and return.
      if (errorList.size() > 0) {
        StringBuffer message = new StringBuffer();
        // Concatenate errors into single message.
        for (int i = 0; i < errorList.size(); i++) {
          message.append(errorList.get(i));
          if (i + 1 < errorList.size()) {
            message.append("\n");
        showError(message.toString());
        return;
      // Remove "www" from start URL if present.
      startUrl = removeWwwFromUrl(startUrl);
      // Start the Search Crawler.
      search(logFile, startUrl, maxUrls, searchString);
    private void search(final String logFile, final String startUrl,
      final int maxUrls, final String searchString)
      // Start the search in a new thread.
      Thread thread = new Thread(new Runnable() {
        public void run() {
          // Show hour glass cursor while crawling is under way.
          setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
          // Disable search controls.
          startTextField.setEnabled(false);
          maxComboBox.setEnabled(false);
          limitCheckBox.setEnabled(false);
          logTextField.setEnabled(false);
          searchTextField.setEnabled(false);
          caseCheckBox.setEnabled(false);
          // Switch Search button to "Stop."
          searchButton.setText("Stop");
          // Reset stats.
          table.setModel(new DefaultTableModel(new Object[][]{},
            new String[]{"URL"}) {
            public boolean isCellEditable(int row, int column)
              return false;
           updateStats(startUrl, 0, 0, maxUrls);
          // Open matches log file.
          try {
            logFileWriter = new PrintWriter(new FileWriter(logFile));
          } catch (Exception e) {
            showError("Unable to open matches log file.");
            return;
          // Turn crawling flag on.
          crawling = true;
          // Perform the actual crawling.
          crawl(startUrl, maxUrls, limitCheckBox.isSelected(),
            searchString, caseCheckBox.isSelected());
          // Turn crawling flag off.
          crawling = false;
          // Close matches log file.
          try {
            logFileWriter.close();
          } catch (Exception e) {
            showError("Unable to close matches log file.");
          // Mark search as done.
          crawlingLabel2.setText("Done");
          // Enable search controls.
          startTextField.setEnabled(true);
          maxComboBox.setEnabled(true);
          limitCheckBox.setEnabled(true);
          logTextField.setEnabled(true);
          searchTextField.setEnabled(true);
          caseCheckBox.setEnabled(true);
          // Switch search button back to "Search."
          searchButton.setText("Search");
          // Return to default cursor.
          setCursor(Cursor.getDefaultCursor());
          // Show message if search string not found.
          if (table.getRowCount() == 0) {
            JOptionPane.showMessageDialog(SearchCrawler.this,
              "Your Search String was not found. Please try another.",
              "Search String Not Found",
              JOptionPane.WARNING_MESSAGE);
      thread.start();
    // Show dialog box with error message.
    private void showError(String message) {
      JOptionPane.showMessageDialog(this, message, "Error",
        JOptionPane.ERROR_MESSAGE);
    // Update crawling stats.
    private void updateStats(
      String crawling, int crawled, int toCrawl, int maxUrls)
      crawlingLabel2.setText(crawling);
      crawledLabel2.setText("" + crawled);
      toCrawlLabel2.setText("" + toCrawl);
      // Update progress bar.
      if (maxUrls == -1) {
        progressBar.setMaximum(crawled + toCrawl);
      } else {
        progressBar.setMaximum(maxUrls);
      progressBar.setValue(crawled);
      matchesLabel2.setText("" + table.getRowCount());
    // Add match to matches table and log file.
    private void addMatch(String url) {
      // Add URL to matches table.
      DefaultTableModel model =
        (DefaultTableModel) table.getModel();
      model.addRow(new Object[]{url});
      // Add URL to matches log file.
      try {
        logFileWriter.println(url);
      } catch (Exception e) {
        showError("Unable to log match.");
    // Verify URL format.
    private URL verifyUrl(String url) {
      // Only allow HTTP URLs.
      if (!url.toLowerCase().startsWith("http://"))
        return null;
      // Verify format of URL.
      URL verifiedUrl = null;
      try {
        verifiedUrl = new URL(url);
      } catch (Exception e) {
        return null;
      return verifiedUrl;
    // Check if robot is allowed to access the given URL. private boolean isRobotAllowed(URL urlToCheck) {
      String host = urlToCheck.getHost().toLowerCase();
      // Retrieve host's disallow list from cache.
      ArrayList disallowList =
        (ArrayList) disallowListCache.get(host);
      // If list is not in the cache, download and cache it.
      if (disallowList == null) {
        disallowList = new ArrayList();
        try {
          URL robotsFileUrl =
            new URL("http://" + host + "/robots.txt");
          // Open connection to robot file URL for reading.
          BufferedReader reader =
            new BufferedReader(new InputStreamReader(
              robotsFileUrl.openStream()));
          // Read robot file, creating list of disallowed paths.
          String line;
          while ((line = reader.readLine()) != null) {
            if (line.indexOf("Disallow:") == 0) {
              String disallowPath =
                line.substring("Disallow:".length());
              // Check disallow path for comments and remove if present.
              int commentIndex = disallowPath.indexOf("#");
              if (commentIndex != -1) {
                disallowPath =
                  disallowPath.substring(0, commentIndex);
              // Remove leading or trailing spaces from disallow path.
              disallowPath = disallowPath.trim();
              // Add disallow path to list.
              disallowList.add(disallowPath);
          // Add new disallow list to cache.
          disallowListCache.put(host, disallowList);
        catch (Exception e) {
          /* Assume robot is allowed since an exception
             is thrown if the robot file doesn't exist. */
          return true;
      /* Loop through disallow list to see if
         crawling is allowed for the given URL. */
      String file = urlToCheck.getFile();
      for (int i = 0; i < disallowList.size(); i++) {
        String disallow = (String) disallowList.get(i);
        if (file.startsWith(disallow)) {
          return false;
      return true;
    // Download page at given URL.
    private String downloadPage(URL pageUrl) {
      try {
        // Open connection to URL for reading.
        BufferedReader reader =
          new BufferedReader(new InputStreamReader(
            pageUrl.openStream()));
        // Read page into buffer.
        String line;
        StringBuffer pageBuffer = new StringBuffer();
        while ((line = reader.readLine()) != null) {
          pageBuffer.append(line);
        return pageBuffer.toString();
      } catch (Exception e) {
      return null;
    // Remove leading "www" from a URL's host if present.
    private String removeWwwFromUrl(String url) {
      int index = url.indexOf("://www.");
      if (index != -1) {
        return url.substring(0, index + 3) +
          url.substring(index + 7);
      return (url);
    // Parse through page contents and retrieve links.
    private ArrayList retrieveLinks(
      URL pageUrl, String pageContents, HashSet crawledList,
      boolean limitHost)
      // Compile link matching pattern.
      Pattern p =
        Pattern.compile("<a\\s+href\\s*=\\s*\"?(.*?)[\"|>]",
          Pattern.CASE_INSENSITIVE);
      Matcher m = p.matcher(pageContents);
      // Create list of link matches.
      ArrayList linkList = new ArrayList();
      while (m.find()) {
        String link = m.group(1).trim();
        // Skip empty links.
        if (link.length() < 1) {
          continue;
        // Skip links that are just page anchors.
        if (link.charAt(0) == '#') {
          continue;
        // Skip mailto links.
        if (link.indexOf("mailto:") != -1) {
          continue;
        // Skip JavaScript links.
        if (link.toLowerCase().indexOf("javascript") != -1) {
          continue;
        // Prefix absolute and relative URLs if necessary.
        if (link.indexOf("://") == -1) {
          // Handle absolute URLs.
          if (link.charAt(0) == '/') {
            link = "http://" + pageUrl.getHost() + link;
          // Handle relative URLs.
          } else {
            String file = pageUrl.getFile();
            if (file.indexOf('/') == -1) {
              link = "http://" + pageUrl.getHost() + "/" + link;
            } else {
              String path =
                file.substring(0, file.lastIndexOf('/') + 1);
              link = "http://" + pageUrl.getHost() + path + link;
        // Remove anchors from link.
        int index = link.indexOf('#');
        if (index != -1) {
          link = link.substring(0, index);
        // Remove leading "www" from URL's host if present.
        link = removeWwwFromUrl(link);
        // Verify link and skip if invalid.
        URL verifiedLink = verifyUrl(link);
        if (verifiedLink == null) {
          continue;
        /* If specified, limit links to those
          having the same host as the start URL. */
        if (limitHost &&
            !pageUrl.getHost().toLowerCase().equals(
              verifiedLink.getHost().toLowerCase())) 
          continue;
        // Skip link if it has already been crawled.
        if (crawledList.contains(link)) {
          continue;
        // Add link to list.
        linkList.add(link);
      return (linkList);
    /* Determine whether or not search string is
       matched in the given page contents. */
    private boolean searchStringMatches(
      String pageContents, String searchString,
      boolean caseSensitive)
      String searchContents = pageContents;
      /* If case-sensitive search, lowercase
         page contents for comparison. */
      if (!caseSensitive) {
        searchContents = pageContents.toLowerCase();
      // Split search string into individual terms.
      Pattern p = Pattern.compile("[\\s]+");
      String[] terms = p.split(searchString);
      // Check to see if each term matches.
      for (int i = 0; i < terms.length; i++) {
        if (caseSensitive) {
          if (searchContents.indexOf(terms) == -1) {
    return false;
    } else {
    if (searchContents.indexOf(terms[i].toLowerCase()) == -1) {
    return false;
    return true;
    // Perform the actual crawling, searching for the search string.
    public void crawl(
    String startUrl, int maxUrls, boolean limitHost,
    String searchString, boolean caseSensitive)
    // Set up crawl lists.
    HashSet crawledList = new HashSet();
    LinkedHashSet toCrawlList = new LinkedHashSet();
    // Add start URL to the to crawl list.
    toCrawlList.add(startUrl);
    /* Perform actual crawling by looping
    through the To Crawl list. */
    while (crawling && toCrawlList.size() > 0)
    /* Check to see if the max URL count has
    been reached, if it was specified.*/
    if (maxUrls != -1) {
    if (crawledList.size() == maxUrls) {
    break;
    // Get URL at bottom of the list.
    String url = (String) toCrawlList.iterator().next();
    // Remove URL from the To Crawl list.
    toCrawlList.remove(url);
    // Convert string url to URL object.
    URL verifiedUrl = verifyUrl(url);
    // Skip URL if robots are not allowed to access it.
    if (!isRobotAllowed(verifiedUrl)) {
    continue;
    // Update crawling stats.
    updateStats(url, crawledList.size(), toCrawlList.size(),
    maxUrls);
    // Add page to the crawled list.
    crawledList.add(url);
    // Download the page at the given URL.
    String pageContents = downloadPage(verifiedUrl);
    /* If the page was downloaded successfully, retrieve all its
    links and then see if it contains the search string. */
    if (pageContents != null && pageContents.length() > 0)
    // Retrieve list of valid links from page.
    ArrayList links =
    retrieveLinks(verifiedUrl, pageContents, crawledList,
    limitHost);
    // Add links to the To Crawl list.
    toCrawlList.addAll(links);
    /* Check if search string is present in
    page, and if so, record a match. */
    if (searchStringMatches(pageContents, searchString,
    caseSensitive))
    addMatch(url);
    // Update crawling stats.
    updateStats(url, crawledList.size(), toCrawlList.size(),
    maxUrls);
    // Run the Search Crawler.
    public static void main(String[] args) {
    SearchCrawler crawler = new SearchCrawler();
    crawler.show();
    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Avoiding new instance

    hi all this is my code
         Set<Person> list = new HashSet<Person>();
              Person p=new Person();
              p.setName("peter");
              list.add(p);
              p.setName("paul");
              list.add(p);
              list.add(new Person("other"));
              list.add(new Person("other"));
         System.out.println(list.size());
              for (Person o : list)
              System.out.println(o.getName());
         the output i see is      
    3
    other
    other
    paul
    I want to know why peter is not considered here? but if i create a new instance it works , why cant i push a same instance twice in a set with two different values
    Person is a simple bean with a name attribute
    Thanks

    j_peter wrote:
    hi all this is my code
         Set<Person> list = new HashSet<Person>();
              Person p=new Person();
              p.setName("peter");
              list.add(p);
              p.setName("paul");
              list.add(p);
              list.add(new Person("other"));
              list.add(new Person("other"));
         System.out.println(list.size());
              for (Person o : list)
              System.out.println(o.getName());
         the output i see is      
    3
    other
    other
    paul
    I want to know why peter is not considered here? but if i create a new instance it works , why cant i push a same instance twice in a set with two different values
    Person is a simple bean with a name attribute
    ThanksI think this can solve your problem,
    p=null;
    p=new Person();
    p.setName("dfasdf");
    p=null;
    p=new Person();
    p.setName("hghg");
    -----

  • List.indexOf

    Guys,
    I have a list with Object type empl:
    long id, //unique
    String name;
    int level.
    I would like to get the index of empl with id X.
    Q: do I have to overwrite the hashCode? what makes the empl unique? , how can I get the index by the id?
    thanks in advance

    The List API says:
    Returns the index in this list of the first occurrence of the specified element, or -1 if this list does not contain this element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
    So, you need to define "equals" appropriately. That is, make your "equals" method compare only the id values--if the id values are equal, return true. Otherwise, return false.
    If you override 'equals', you should often override 'hashCode'. But, if you aren't using any HashMap/HashSet, you probably won't actually need hashCode.

  • Please Help::How to display a Map with LIsts as Keys and Values using JSTL

    Hi,
    I need some assistance on how to display a Map in JSP using struts or core JSTL. I have a HashMap which has a List of keys and each key maps to a value of an ArrayList.i.e I have an ArrayList of taxCodes and each taxCode maps to a value of taxDetails which is an ArrayList of details for for that particular taxCode. I have some trouble to display each taxCode then display taxDetails for each taxCode. Here is my code below:
    OrderDetails.java
    package orderitems;
    import java.sql.*;
    import java.util.*;
    public class OrderDetails {
        private LineOder lineOrder;
        private Map lineItems;
        //returns an item number, key_item, from its unique keys
        public int getItemNumber(int key_item, String key_year,
                String key_office,String key_client,String key_company){
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            int itmNum = 0;
             * key_item a unique number for an item.
             * key_year,key_office,key_client,key_company unique keys
             * for each order where this key_item is taken
             * from.
            String select = "SELECT key_item FROM "+
                    Constants.WEB_TABLE +" WHERE key_item = " + key_item +
                    " AND key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company +"'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                if(rst.next()){
                    itmNum = Integer.parseInt(rst.getString("key_item"));
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return itmNum;
        //get a list of item number(item codes)
        public List getAllItemNumbers(String key_year,
                String key_office,String key_client,String key_company){
            List itemNumbers = new ArrayList();
            LineItem itemNumber = null;
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            String select = "SELECT key_item FROM "+ Constants.WEB_TABLE +
                    " WHERE key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company + "'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                while(rst.next()){
                    itemNumber = new LineItem();
                    itemNumber.setKey_item(Integer.parseInt(rst.getString("key_item")));
                    itemNumbers.add(itemNumber);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return itemNumbers;
        //get a list of tax codes
        public List getAllTaxCodes(int key_item, String key_year,
                String key_office,String key_client,String key_company){
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            ItemTax taxCode;
            List taxCodes = new ArrayList();
            int itemNum = getItemNumber(key_item, key_year,
                    key_office,key_client,key_company);
            String select = "SELECT key_tax_code FROM "+
                    Constants.WEB_TABLE +" WHERE key_item = " + itemNum +
                    " AND key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company +"'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                while(rst.next()){
                    taxCode = new ItemTax();
                    taxCode.setKey_tax_code(rst.getString("key_tax_code"));
                    taxCodes.add(taxCode);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return taxCodes;
        /////This methode returns a Map which am trying to display in JSP
        //use tax code to get tax details
        public Map getItemTaxDetails(String key_year,String key_office,
                String key_client,String key_company,int key_item){
            ItemTax taxDetail = null;
            List taxDetails = new ArrayList();
            List itemTaxCodes = new ArrayList();
            Map itemTaxDetails = new HashMap();
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            //get a list of all tax codes of an item with a
            //given item number
            itemTaxCodes = getAllTaxCodes(key_item,key_year,
                    key_office,key_client,key_company);
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                for(Iterator taxCodeIter= itemTaxCodes.iterator(); taxCodeIter.hasNext();){
                    ItemTax itemTaxCode = (ItemTax)taxCodeIter.next();
                    String taxCode = itemTaxCode.getKey_tax_code();
                    String select = "SELECT tax_type,tax_value," +
                            "tax_limit_val FROM "+ Constants.WEB_TABLE +
                            " WHERE key_item = "+ key_item +
                            " AND key_year = '" + key_year + "'" +
                            " AND key_office = '" + key_office + "'" +
                            " AND key_client = '" + key_client + "'" +
                            " AND key_company = '" + key_company +"'" +
                            " AND key_tax_code = '" + taxCode + "'";
                    rst = stat.executeQuery(select);
                    while(rst.next()){
                        taxDetail = new ItemTax();
                        //records to be displayed only
                        taxDetail.setKey_item(Integer.parseInt(rst.getString("key_item")));
                        taxDetail.setTax_value(rst.getString("tax_value"));
                        taxDetail.setTax_limit_val(Float.parseFloat(rst.getString("tax_limit_val")));
                        //////other details records ommited//////////////////////////
                        taxDetails.add(taxDetail);////An ArrayList of taxDetails for each taxCode
                     * A HashMap which has all taxCodes of an item as its keys
                     * and an ArrayList of taxdetails as its values.
                     * I return this for display in a JSP.
                    itemTaxDetails.put(taxCode,taxDetails);
                System.out.println();
                System.out.println("*********CONSOLE OUTPUT*************");//display on console
                Set set = itemTaxDetails.keySet();
                Iterator iter = set.iterator();
                System.out.println("Key\t\tValue\r\n");
                while (iter.hasNext()) {
                    Object taxCode=iter.next();
                    Object details=itemTaxDetails.get(taxCode);
                    System.out.println(taxCode +"\t" + details);
                System.out.println("************************************");
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return itemTaxDetails;
        //details of an item with all its taxes
        public List getAllItemDetails(String key_year,
                String key_office,String key_client,String key_company){
            List lineItems = new ArrayList();
            List itemNumbers = new ArrayList();
            Map taxDetails = new HashMap();
            LineItem item = null;
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            //A list of all item numbers in the declaration
            itemNumbers = getAllItemNumbers(key_year,
                    key_office,key_client,key_company);
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                for(Iterator itemIter= itemNumbers.iterator(); itemIter.hasNext();){
                    LineItem itemNum = (LineItem)itemIter.next();
                    int itemNumber = itemNum.getKey_item();
                    String select = "SELECT item_description,item_mass," +
                            "item_cost" +
                            " FROM " + Constants.WEB_TABLE +
                            " WHERE key_year = '"+key_year+"'" +
                            " AND key_office = '"+key_office+ "'"+
                            " AND key_client = '"+key_client+ "'"+
                            " AND key_company = '"+key_company+ "'"+
                            " AND key_item = " + itemNumber;
                    rst = stat.executeQuery(select);
                    while(rst.next()){
                        item = new LineItem();
                        item.setItem_description(rst.getString("item_description"));
                        item.setItem_mass(Float.parseFloat(rst.getString("item_mass")));
                        item.setKey_item(Integer.parseInt(rst.getString("item_cost")));
                        //////other details records ommited//////////////////////////
                        /* A HashMap of all itemTaxeCodes as its keys and an
                         * ArrayList of itemTaxedetails as its values
                        taxDetails = getItemTaxDetails(item.getKey_year(),item.getKey_office(),
                                item.getKey_client(),item.getKey_company(),item.getKey_item());
                        //item tax details
                        item.setItmTaxes(taxDetails);
                        //list of items with tax details
                        lineItems.add(item);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return lineItems;
        public Set getOrders(String key_year,String key_office,
                String key_client,String key_company){
            List lineItems = new ArrayList();
            Set lineOrders = new HashSet();
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            LineOder lineOrder = null;
            String select = "SELECT * FROM " + Constants.WEB_TABLE +
                    " WHERE key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company + "'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                while(rst.next()){
                    lineOrder = new LineOder();
                    lineOrder.setKey_year(rst.getString("key_year"));
                    lineOrder.setKey_office(rst.getString("key_office"));
                    lineOrder.setKey_client(rst.getString("key_client"));
                    lineOrder.setKey_company(rst.getString("key_company"));
                    ////list of items with all their details
                    lineItems = getAllItemDetails(lineOrder.getKey_year(),lineOrder.getKey_office(),
                            lineOrder.getKey_client(),lineOrder.getKey_company());
                    //setting item details
                    lineOrder.setItems(lineItems);
                    //a list of order with all details
                    lineOrders.add(lineOrder);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return lineOrders;
    Controller.java
    package orderitems;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Controller extends HttpServlet {
        private Map taxDetails = new HashMap();
        private OrderDetails orderDetails = null;
        protected void processRequest(HttpServletRequest request,
                HttpServletResponse response)throws
                ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            String key_year = "2007";
            String key_office = "VZX00";
            String key_company = "DG20";
            String key_client =  "ZI001";
            int key_item = 1;
            String nextView = "/taxdetails_list.jsp";
            orderDetails = new OrderDetails();
            taxDetails = orderDetails.getItemTaxDetails(key_year,key_office,
                    key_company,key_client,key_item);
            //Store the collection objects into HTTP Request
            request.setAttribute("taxDetails", taxDetails);
            RequestDispatcher reqstDisp =
                    getServletContext().getRequestDispatcher(nextView);
            reqstDisp.forward(request,response);
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response)throws
                ServletException, IOException {
            processRequest(request, response);
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response)throws
                ServletException, IOException {
            processRequest(request, response);
    taxdetails_list.jsp
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <title>Simple Tax Detail Diaplay ::</title>
            <link rel="stylesheet" type="text/css" href="imgs/orders.css"/>
        </head>
        <body>
            <jsp:useBean id="taxDetails" class="java.util.HashMap" scope="request"/>
            <table>
                <c:forEach items="${taxDetails}" var="hMap">
                    <tr>
                        <td><c:out value="${hMap.key}" /></td>
                        <!--td><%--c:out value="${hMap.value}" /--%></td-->
                    </tr>
                </c:forEach>
            </table>
        </body>
    </html>am displaying taxCodes(in this case i have VAT and ICD) fine but cant figure out how to display a list of value for each taxCode.Here is the output am getting
    both in my JSP and on the console:
    *******************************CONSOLE OUTPUT****************************
    Key          Value
    ICD     [orderItems.ItemTax@13e6226, orderItems.ItemTax@9dca26]
    VAT [orderItems.ItemTax@13e6226, orderItems.ItemTax@9dca26]
    Edited by: aiEx on Oct 8, 2007 6:54 AM

    hi evnafets,
    yes i need a nested for loop.I have tried your advice but my bean properties are not found.Am getting this error:
    javax.servlet.ServletException: Unable to find a value for "key_item" in object of class "java.lang.String" using operator "."
    I have tried this as stated earlier in the post:I have tried to make the method getItemTaxDetails return a List and get the returned list value as taxDetails. I then tested to display this list on JSP and its displaying fine.
    public List getItemTaxDetails(String key_year,String key_office,
                String key_client,String key_company,int key_item){
            ItemTax taxDetail = null;
            List taxDetails = new ArrayList();
            List itemTaxCodes = new ArrayList();
            Map itemTaxDetails = new HashMap();
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            //get a list of all tax codes of an item with a
            //given item number
            itemTaxCodes = getAllTaxCodes(key_item,key_year,
                    key_office,key_client,key_company);
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                for(Iterator taxCodeIter= itemTaxCodes.iterator(); taxCodeIter.hasNext();){
                    ItemTax itemTaxCode = (ItemTax)taxCodeIter.next();
                    String taxCode = itemTaxCode.getKey_tax_code();
                    String select = "SELECT tax_type,tax_value," +
                            "tax_limit_val FROM "+ Constants.WEB_TABLE +
                            " WHERE key_item = "+ key_item +
                            " AND key_year = '" + key_year + "'" +
                            " AND key_office = '" + key_office + "'" +
                            " AND key_client = '" + key_client + "'" +
                            " AND key_company = '" + key_company +"'" +
                            " AND key_tax_code = '" + taxCode + "'";
                    rst = stat.executeQuery(select);
                    while(rst.next()){
                        taxDetail = new ItemTax();
                        //records to be displayed only
                        taxDetail.setKey_item(Integer.parseInt(rst.getString("key_item")));
                        taxDetail.setTax_value(rst.getString("tax_value"));
                        taxDetail.setTax_limit_val(Float.parseFloat(rst.getString("tax_limit_val")));
                        //////other details records ommited//////////////////////////
                        taxDetails.add(taxDetail);////An ArrayList of taxDetails for each taxCode
                     * A HashMap which has all taxCodes of an item as its keys
                     * and an ArrayList of taxdetails as its values.
                     * I return this for display in a JSP.
                    itemTaxDetails.put(taxCode,taxDetails);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            //return itemTaxDetails;
            return taxDetails;
        }And my JSP
    taxdetails_list.jsp
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <link rel="stylesheet" type="text/css" href="imgs/orders.css"/>
        </head>
        <body>
            <table>
                <c:forEach var="curRecord" items="${taxDetails}" varStatus="rowCounter">
                        <c:choose>
                            <c:when test="${rowCounter.count % 2 == 0}">
                                <c:set var="rowStyle" scope="page" value="odd" />
                            </c:when>
                            <c:otherwise>
                                <c:set var="rowStyle" scope="page" value="even" />
                            </c:otherwise>
                        </c:choose>
                        <tr class="${rowStyle}">
                            <td>${curRecord.key_item}</td>
                            <td>${curRecord.tax_value}</td>
                            <td>${curRecord.tax_limit_val}</td>
                        </tr>
                    </c:forEach>
            </table>
        </body>
    </html>I can't see where am going wrong even with your advice.Please help.
    Thnx.

  • HashSet doesnt remove duplicates

    Hello
    I am trying to remove duplicates from a list using this code
    Set set = new HashSet();
    ListIterator li = list.listIterator();
    while (li.hasNext())
                   A pt = (A) li.next();
                   duplicate = pt.getID(); //duplicate is declared globally
                    if (!set.add(pt))
                        System.out.println("Duplicate found: " + pt.getID());
               }but it isnt removing duplicates. I read somewhere that I should override the equals() and hashCode() methods. But I am a bit confused as to how to write my equals method. The list contains objects of class A, which has many getters and setters. The elements are considered to be duplicate when getID() getter returns same value for two objects. Can some one tell me how should i go about writing the equals method. And why the default equals method for objects isnt working in this case?
    This is how i tried to write my equals() method but it isnt working
    public boolean equals(Object o)
           if (o == this)
                 return true;
            if (!(o instanceof A))
                 return false;
            A pn =  (A) o;
            return pn.getID() == duplicate; // duplicate has been set before calling add
         }

    Sorry if I got confusing about what I was trying to say. I was actually trying to expand on your earlier post, where you mentioned that the class needs the proper implementation of equals() had hashCode().
    I went over this with one of my programmers fairly recently. He was having a hard time understanding why he was getting a false when the contents of the object were the same. Of course he did not override the equals() method and was doing an object comparison, and not one on the contents of the objects.
    Maybe the following examples will better illustrate what I was trying to say.
    Without equals:
    public class EqualityExample {
         public EqualityExample()
          * @param args
         public static void main(String[] args) {
              EqualityExample ee = new EqualityExample();
              // TODO Auto-generated method stub
              DataClass testObject1 = ee.new DataClass("A String");
              DataClass testObject2 = ee.new DataClass("A String");
              if (testObject1.equals(testObject2))
                   System.out.println("are equal");
              else
                   System.out.println("not equal");
         public class DataClass
              private String someVal;
              public DataClass(String someVal)
                   this.someVal = someVal;
    }With equals:
    public class EqualityExample {
         public EqualityExample()
          * @param args
         public static void main(String[] args) {
              EqualityExample ee = new EqualityExample();
              // TODO Auto-generated method stub
              DataClass testObject1 = ee.new DataClass("A String");
              DataClass testObject2 = ee.new DataClass("A String");
              if (testObject1.equals(testObject2))
                   System.out.println("are equal");
              else
                   System.out.println("not equal");
         public class DataClass
              private String someVal;
              public DataClass(String someVal)
                   this.someVal = someVal;
              public boolean equals(DataClass object)
                   if (object.someVal == this.someVal)
                        return true;
                   else
                        return false;
    }

  • How to merge 2 lists in java in the class definition

    Hello, please help me. I am totally
    I have been writing a class articleList.
    I need to merge articleList 1 with articleList 2 to get a new list containing all items from articleList 1 and articleList 2, no double items required.
    How can I implement this in the articleList class?
    I have this already
    // this method merges 2 lists together
    public void merge (List a, List b)
    what to put here?
    Please help?

    Create a HashSet and add all items from both liststo
    that set. Do then create a List from that Set.
    KajWhether data redundancy can be solved by HashSet, Kaj?Yes. A set does not allow duplicates. Isn't that what he wanted to do? Remove duplicates from the result?
    Kaj

  • Select distinct using LINQ and bound to a dropdown list with id and display name

    Hi,
    On one of my sharepoint page, I want to populate dropdown list with countries, namely
    <asp:DropDownList ID="ddlCountry" runat ="server"></asp:DropDownList>
    In the code, I use LINQ:
     var country = (from p in dc.ProvCountries
                                   select p.country_code ).Distinct();
                ddlCountry.DataSource = country;
                    ddlCountry.DataBind();
    I want the country_code to be  the ID, while the country_name will be the display name in the dropdown, how can that be done?
    Thanks in advance.

    Hi,
    The following code for your check.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    namespace WebApplicationLib
    public partial class _Default : Page
    protected void Page_Load(object sender, EventArgs e)
    List<ProvCountries> list = new List<ProvCountries>();
    list.Add(new ProvCountries { country_code = "201", country_name = "A"});
    list.Add(new ProvCountries { country_code = "201", country_name = "B" });
    list.Add(new ProvCountries { country_code = "202", country_name = "C" });
    list.Add(new ProvCountries { country_code = "202", country_name = "D" });
    var country = (from p in list select new { p.country_code, p.country_name }).DistinctBy(p => p.country_code).ToList();
    ddlCountry.DataSource = country;
    ddlCountry.DataValueField = "country_code";
    ddlCountry.DataTextField = "country_name";
    ddlCountry.DataBind();
    ddlCountry.Items.Insert(0, new ListItem("Please select", ""));
    class ProvCountries
    public string country_code { get; set; }
    public string country_name { get; set; }
    static class DataDistinct
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
    if (seenKeys.Add(keySelector(element)))
    yield return element;
    Thanks,
    Dennis Guo
    TechNet Community Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Dennis Guo
    TechNet Community Support

  • Adding parentheses to each item in HashSet

    Dear All,
    Having almost completed my first java tool which queries a database to allow user-defined filtering, I'm running into a last 'small' problem:
    I won't bore you guys with the whole thing, but instead will just focus on the part where i'm stuck, in the hope that somebody can give me a useful tip as to how to solve this! Thanks very much in advance for any input!
    Basically, what it comes down to is that I query the database twice, resulting in two lists of data stored as HashSets in Java, to then work out the intersect of them both with the listI.retainAll(listII) function. Finally, I want to use the merged list to query the database again, using the variables listed in the final set. In order to use the list in the query, I first convert the HashSet to a string as follows:
    String convList = listI.toString();As this results in a string with square brackets [] and mySQL needs regular brackets, I convert them like this:
    convList = convList.replace('[', '(');
    convList = convList.replace(']', ')');This will result in something along the lines as (result1, result2, result3, result4, etc.). The problem is though, that I would need it to be like
    ("result1", "result2", "result3", "result4") in order for mySQL to accept it using the IN clause.
    I tried to add the parentheses using:
    convList = convList.replaceAll(',', '",');
            convList = convList.replaceAll(' ', ' "');but the Java compiler complains of an error with "unclosed character literal", so I was hoping somebody could maybe give me a hint as to how I can add parentheses for each member in the list? Thanks alot in advance

    les_paulde wrote:
    wow, thanks for your swift reply! This definitely solved my problem and I can now run the query. The code turned out as follows:
    String convList = listI.toString();
    convList = convList.replace("[", "(\"");
    convList = convList.replace("]", "\")");
    convList = convList.replaceAll(",", "\",");
    convList = convList.replaceAll(" ", " \"");
    And what happens if the String representation of the object in your list contains one of the characters you're replacing? It will go awfully wrong!
    This is safer:
    public static String asString(List<?> list) {
        StringBuilder b = new StringBuilder();
        b.append('(');
        for(int i = 0; i < list.size(); i++) {
            b.append('"').append(list.get(i)).append('"');
            if(i < list.size()-1) b.append(", ");
        return b.append(')').toString();
    System.out.println(asString(listI));

  • How to "quick search" in a sorted list ?

    Hi all,
    I need that your advice to choose the best collection to modelize my data.
    Let me describe you the context of my problem:
    I work on an antenna pattern file which looks like this:
    Elevation (deg);Gain (dB)
    0;5
    3;45
    6;3.1
    10;6.5
    16;18.1
    20;33.1
    24;31.2
    30;3.5 I need, for a given elevation angle, to get the related gain. if the exact value of the angle is not found, we will return the gain of the nearest angle.
    For example:
    If the elevation angle is 5 degrees, I must return 3.1 dB.This operation should be called a big number of time (about many hundred calls)
    What are your advices to modelize my data ? What is the best collection to do it ? What is the best way to quick search in this data to get the gain realted to a given angle ?
    I though to use the binary search tree. What do you think about this solution ? Do you known of the Java API contains an implementation of the binary search trees ?
    I though too to use an hashset. The hashcode should be computed in order to access to the nearest angle in the list of values. But I did not find the alogrithm to compute a such hash code. Maybe it is a wrong way.
    Please, help me.
    Tell me your opinion and your advices to solve my problem.
    Let me know if you need more information
    Thanks

    OK, it works.
    I created a class for my data:public class ElGainPatternElement
      private double elevation;
      private double gain;
    +getters/setters
    }Then, I created a comparator to compare my elements on the elevation attribute.
    Finally, I specialiazed the Collections.binarySearch method in order to return the value instead of the index.
    I the object is not found, I return the inferior (or superior) object.
    public static <T> T binarySearch(List<? extends T> list, T key,
          Comparator<? super T> c, boolean isMinStrategy)
        int index = Collections.binarySearch(list, key, c);
        // si objet non trouv�
        if (index < 0)
          // r�cup�rer l'index le plus proche de celui recherch�
          index = isMinStrategy ? (-index - 2) : (-index - 1);
          // si plus grand que tous les �lts, retourner le dernier de la liste
          if (index >= list.size())
            index = list.size() - 1;
          // si plus grand que tous les �lts, retourner le premier de la liste
          else if (index < 0)
            index = 0;
        // retourner l'objet le plus proche au regard de la strat�gie
        return list.get(index);
      }It works very well.
    But now, I need to change the strategy to use if the wanted elevation is not in the list.
    If you look at the example of my first post, the 5 degrees of elevation is not in my list. So, I have to interpolate the values of the gain in order to get a correct gain.
    If possible, it should use the least squares interpolation (I'm not sure of my traduction of "moindres carr�s").
    I have really no idea of the way to do it.
    Can anyone help me with this interpolation ? I have never use algorithm of interpolation (except the mean of 2 values).
    Maybe the Java API provides some utilities that can help me to interpolate my values ... any suggestions ?
    Thanks

  • A suggestion : use "loop array list" instead of ArrayList / LinkedList

    ArrayList is good at:
    get / set by index : O(1)
    appending : O(log(n))
    remove last : O(1)
    and very bad at:
    add middle : O(n)
    remove from middle : O(n)
    LinkedList is good at:
    fast remove from middle, if your iteraror already goes there : O(1)
    convenient methods : addFirst, addLast, removeFirst, removeLast : O(1)
    and very bad at :
    get / set by index : O(n)
    here I want to make a suggestion : use "loop array list" instead of the ArrayList and LinkedList.
    a "loop array list" is based on array, just like ArrayList. But it has 2 member-variables : the start position, and the real size. the start position can be anywhere within array.length. an element of index "i" is stored in array[ start + i ], and when (start + i > array.length), loop to the beginning of the array; when (start + i < 0), loop to the end of the array.
    this "loop array list" has all the good sides:
    get / set by index : O(1)
    add first / last : O(log(n))
    remove first / last : O(log(n))
    add / remove from middle : O(n)
    (note : because we shrink the backup-array when the real size is too small, add / remove operation take O(log(n)) now.)
    the only problem is : add / remove from middle. let's take a look at it.
    1. the LinkedList does NOT really add/remove from middle in O(1), you has to locate the element, which is O(n).
    2. O(n) is acceptable, O(n^2) is not acceptable. try this : keep removing first element from an very big ArrayList ( size>10^6 ) until it's empty.
    the fact is, any list can perform batch-remove / batch-add operation in O(n) instead of O(n^2). it's easy : allocate a new list, iterate the original list, copy the element into the new list if condition is satisfied.
    so, instead of "remove from middle", what we need is a new methods : removeAllByCondition( Condition condition ), and now the batch-remove operation can be done in O(n)
    here is an implementation of mine. I've tested it on my computer( 512mem + 2G cpu, win2k + jdk1.5 ), it's amazing, just a little slower then ArrayList when add last, and a liitle slower then LinkedList when batch-remove. in all other cases, it's far more better then those 2 kinds of List.
    // source code : List2
    import java.util.AbstractList;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.NoSuchElementException;
    import java.util.Set;
    public final class List2<T> extends AbstractList<T> {
    private static int initialArrayLength = 4;
    private T[] array;
    private int start;
    private int size;
    private void init( T[] newArray, int start_a, int size_a ) {
    array = newArray;
    start = start_a;
    size = size_a;
    @SuppressWarnings("unchecked")
    private void init() {
    init( (T[]) new Object[ initialArrayLength ], 0, 0 );
    public List2() {
         init();
    @SuppressWarnings("unchecked")
    public List2( Collection<? extends T> collection ) {
         init(
              collection.toArray( (T[]) new Object[ collection.size() * 11 / 10 + 1 ] ),
              0,
              collection.size()
    private List2( T[] array_a, int start_a, int size_a ) {
         init( array_a, start_a, size_a );
    @SuppressWarnings("unchecked")
    public static <TT> List2<TT> createV( TT... elements ) {
         TT[] array = (TT[]) new Object[ elements.length * 11 / 10 + 1 ];
         System.arraycopy( elements, 0, array, 0, elements.length );
         return new List2<TT>( array, 0, elements.length );
    public static List2<Double> create( double... elements ) {
         Double[] array = new Double[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array[i] = elements;
         return new List2<Double>( array, 0, elements.length );
    public static List2<Integer> create( int... elements ) {
         Integer[] array2 = new Integer[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array2[i] = elements[i];
         return new List2<Integer>( array2, 0, elements.length );
    public static List2<Character> create( char... elements ) {
         Character[] array2 = new Character[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array2[i] = elements[i];
         return new List2<Character>( array2, 0, elements.length );
    public static List2<Character> create( String s ) {
         return create( s.toCharArray() );
    public List2<T> clone() {
         return new List2<T>( this );
    // basic
    public int size() {
         return size;
    private int index( int index ) {
         int i = start + index;
         if( i >= array.length )
              i -= array.length;
         return i;
    public T get( int d ) {
         if( d < 0 || d >= size )
              throw new IndexOutOfBoundsException();
         if( size == 0 )
              throw new NoSuchElementException();
         return array[ index( d ) ];
    public T set( int index, T element ) {
         if( index < 0 || index >= size )
              throw new IndexOutOfBoundsException();
         int i = index( index );
         T oldElement = array[i];
         array[i] = element;
         return oldElement;
    @SuppressWarnings("unchecked")
    private void copyAndSetToNewArray( int newArrayLength ) {
         T[] newArray = (T[]) new Object[ newArrayLength ];
         for( int i=0; i<size; i++ )
              newArray[i] = array[ index( i ) ];
         init( newArray, 0, size );
    public void addFirst( T element ) {
         if( size == array.length )
              copyAndSetToNewArray( size * 3 / 2 + 1 );
         int i = index( array.length - 1 );
         array[ i ] = element;
         start = i;
         size++;
    public void addLast( T element ) {
         if( size == array.length )
              copyAndSetToNewArray( size * 3 / 2 + 1 );
         array[ index( size ) ] = element;
         size++;
    public T removeFirst() {
         if( size == 0 )
              throw new NoSuchElementException();
         T oldElement = array[ start ];
         array[ start ] = null;
         start = index( 1 );
         size--;
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return oldElement;
    public T removeLast() {
         if( size == 0 )
              throw new NoSuchElementException();
         int i = index( size - 1 );
         T oldElement = array[i];
         array[i] = null;
         size--;
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return oldElement;
    @SuppressWarnings("unchecked")
    public int removeAll( ListCondition<T> condition ) {
         T[] newArray = (T[]) new Object[ array.length ];
         int iNew = 0;
         for( int i=0; i < size; i++ ) {
              T element = get( i );
              if( ! condition.isConditionSatisfied( this, i, element ) )
                   newArray[ iNew++ ] = element;
         int oldSize = size;
         init( newArray, 0, iNew );
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return size - oldSize;
    // aux
    public boolean equals(Object obj) {
         if( obj == this )
         return true;
         if( obj instanceof List2 ) {
              List2 that = (List2) obj;
              if( this.size != that.size )
                   return false;
              for( int i=0; i < size; i++ )
                   if( ! Tools.equals( this.array[ this.index(i) ], that.array[ that.index(i) ] ) )
                        return false;
              return true;
         if( obj instanceof List ) {
              List that = (List) obj;
              if( this.size != that.size() )
                   return false;
              Iterator thatIter = that.iterator();
              for( int i=0; i < size; i++ )
                   if( ! Tools.equals( this.array[ this.index(i) ], thatIter.next() ) )
                        return false;
              return true;
         return true;
    public int hashCode() {
         int hashCode = 1;
         for( int i=0; i < size; i++ ) {
              T element = array[ index( i ) ];
         hashCode = 31*hashCode + ( element==null ? 0 : element.hashCode() );
         return hashCode;
    public boolean isEmpty() {
         return size == 0;
    public T getFirst() {
         return get( 0 );
    public T getLast() {
         return get( size() - 1 );
    public T getRandom() {
         return get( (int) (Math.random() * size) );
    public int indexOf( Object element ) {
         for( int i=0; i < size; i++ )
              if( Tools.equals( array[ index( i ) ], element ) )
                   return i;
         return -1;
    public int lastIndexOf( Object element ) {
         for( int i=size-1; i >= 0; i-- )
              if( Tools.equals( array[ index( i ) ], element ) )
                   return i;
         return -1;
    public boolean contains( Object element ) {
         return indexOf( element ) != -1;
    public boolean add( T element ) {
         addLast( element );
         return true;
    @Deprecated
    public void add( int index, T element ) {
         throw new UnsupportedOperationException();
    public T remove() {
         return removeFirst();
    @Deprecated
    public boolean remove( Object element ) {
         throw new UnsupportedOperationException( "use removeAll( Condition ) instead" );
    @Deprecated
    public T remove( int index ) {
         throw new UnsupportedOperationException( "use removeAll( Condition ) instead" );
    public void clear() {
         init();
    public Object[] toArray() {
         Object[] result = new Object[ size ];
         for( int i=0; i < size; i++ )
         result[i] = array[ index( i ) ];
         return result;
    @SuppressWarnings("unchecked")
    public <TT> TT[] toArray( TT[] a ) {
    if( a.length < size )
    a = (TT[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size );
    for( int i=0; i < size; i++ )
    a[i] = (TT) array[ index( i ) ];
    if( a.length > size )
         a[size] = null;
    return a;
    @SuppressWarnings("unchecked")
    public void sort() {
         Object[] a = toArray();
         Arrays.sort( a );
         for( int i=0; i < size; i++ )
              array[ i ] = (T) a[ i ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sortDesc() {
         Object[] a = toArray();
         Arrays.sort( a );
         for( int i=0, j=size-1; i < size; i++, j-- )
              array[ i ] = (T) a[ j ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sort( Comparator<T> comparator ) {
         T[] a = (T[]) toArray();
         Arrays.sort( a, comparator );
         for( int i=0; i < size; i++ )
              array[ i ] = a[ i ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sortDesc( Comparator<T> comparator ) {
         T[] a = (T[]) toArray();
         Arrays.sort( a, comparator );
         for( int i=0, j=size-1; i < size; i++, j-- )
              array[ i ] = a[ j ];
         start = 0;
    public String toString( String delimiter ) {
         return toString( "", delimiter, "", size() );
    public String toString( String prefix, String delimiter, String suffix, int max ) {
         StringBuffer stringBuffer = new StringBuffer( prefix );
         int dest = Math.min( max, size );
         for( int i=0; i < dest; i++ ) {
              stringBuffer.append( get(i) );
              if( i < dest - 1 )
                   stringBuffer.append( delimiter );
         if( size > max )
              stringBuffer.append( "...(" ).append( size() - max ).append( " more)" );
         stringBuffer.append( suffix );
         return stringBuffer.toString();
    // batch operation
    public boolean containsAll( Collection<?> that ) {
         Set<Object> thisSet = new HashSet<Object>( this );
         for( Object element : that )
              if( ! thisSet.contains( element ) )
                   return false;
         return true;
    @SuppressWarnings("unchecked")
    public List2<T> subList( int fromIndex, int toIndex ) {
         if( fromIndex < 0 || toIndex > size || toIndex < fromIndex )
              throw new IndexOutOfBoundsException();
         int newSize = toIndex - fromIndex;
         T[] newArray = (T[]) new Object[ newSize * 11 / 10 + 1 ];
         for( int i=fromIndex, iNew=0; i < toIndex; i++, iNew++ )
              newArray[ iNew ] = array[ index( i ) ];
         return new List2<T>( newArray, 0, newSize );
    public void addV( T... that ) {
         for( T element : that )
              addLast( element );
    public boolean addAll( Collection<? extends T> that ) {
         for( T element : that )
              addLast( element );
         return ! that.isEmpty();
    @Deprecated
    public boolean addAll( int index, Collection<? extends T> c ) {
         throw new UnsupportedOperationException();
    public void removeRest( T element ) {
         int position = lastIndexOf( element );
         if( position == -1 )
              return;
         while( ! Tools.equals( element, removeLast() ) );
    public void removeAllEquals( final T element ) {
         removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T currentElement) {
              return currentElement.equals( element );
    public void removeAllBetween( final T from, final T to ) {
         removeAll( new ListCondition<T>() {
              @SuppressWarnings("unchecked")
              public boolean isConditionSatisfied(List2 list, int index, T element) {
                   if( from != null && ((Comparable) from).compareTo( element ) > 0 )
                        return false;
                   if( to != null && ((Comparable) to).compareTo( element ) <= 0 )
                        return false;
                   return true;
    public boolean retainAll( Collection<?> that ) {
         final Set<Object> thatSet = new HashSet<Object>( that );
         int removeCount = removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T element) {
              return ! thatSet.contains( element );
         return removeCount > 0;
    public boolean removeAll( Collection<?> that ) {
         final Set<Object> thatSet = new HashSet<Object>( that );
         int removeCount = removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T element) {
              return thatSet.contains( element );
         return removeCount > 0;
    // unit test
    private static int maxTestCount = 1000 * 1000;
    public static void unitTest() throws Exception {
         // thest thoese methods for one time
         Tools.ensureEquals( new List2(), new ArrayList() );
         Tools.ensureNotEquals( List2.create( "abcde" ), new ArrayList() );
         Tools.ensureNotEquals( List2.create( "abcde" ), List2.create( "abcdef" ) );
         final List<Double> list1 = new ArrayList<Double>();
         final List2<Double> list2 = new List2<Double>();
         Runnable[] tasks = new Runnable[] {
              // test those methods that do NOT change the list
              new Runnable() { public void run() {
                   Tools.ensureEquals( new List2<Double>( list1 ), list1 );
                   Tools.ensureEquals( List2.createV( list1.toArray() ), list1 );
                   Tools.ensureEquals( List2.createV( list1.toArray( new Double[0] ) ), list1 );
                   double[] doubles = new double[ list1.size() ];
                   int i = 0;
                   for( double d : list1 )
                        doubles[i++] = d;
                   Tools.ensureEquals( List2.create( doubles ), list1 );
                   Tools.ensure( list1.isEmpty() == list2.isEmpty() );
                   Arrays.equals( list1.toArray(), list2.toArray() );
                   Tools.ensureEquals( list1, list2.clone() );
                   Double notExistElement = -2.0;
                   Tools.ensure( list1.indexOf( notExistElement ) == -1 );
                   Tools.ensure( list1.lastIndexOf( notExistElement ) == -1 );
                   Tools.ensure( list1.contains( notExistElement ) == false );
                   Tools.ensureEquals( list1.toString(), list2.toString() );
                   Tools.ensureEquals( list1.toString(), list2.toString() );
                   Tools.ensureEquals( list1.hashCode(), list2.hashCode() );
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.get(0).equals( list2.getFirst() ) );
                   Tools.ensure( list1.get(list1.size()-1).equals( list2.getLast() ) );
                   Double existRandomElement = list2.getRandom();
                   Tools.ensure( list1.contains( existRandomElement ) );
                   Tools.ensure( list2.contains( existRandomElement ) );
                   Tools.ensure( list1.indexOf( existRandomElement ) == list2.indexOf( existRandomElement ) );
                   Tools.ensure( list1.indexOf( existRandomElement ) == list2.indexOf( existRandomElement ) );
                   int from = (int) (Math.random() * list1.size());
                   int to = (int) (Math.random() * (list1.size()+1));
                   if( from > to ) {
                        int t = from;
                        from = to;
                        to = t;
                   Tools.ensureEquals( list1.subList( from, to ), list2.subList( from, to ) );
              // test those methods that change the list
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = (int) (Math.random() * list1.size());
                   double d = Math.random();
                   list1.set( i, d );
                   list2.set( i, d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = (int) (Math.random() * list1.size());
                   Tools.ensure( list1.get( i ).equals( list2.get( i ) ) );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( 0, d );
                   list2.addFirst( d );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.addLast( d );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.addLast( d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove( 0 ).equals( list2.removeFirst() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove( list1.size() - 1 ).equals( list2.removeLast() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = 0;
                   for( Iterator<Double> iter=list1.iterator(); iter.hasNext(); i++ ) {
                        iter.next();
                        if( i % 3 == 0 )
                             iter.remove();
                   list2.removeAll( new ListCondition<Double>() { public boolean isConditionSatisfied(List2 list, int index, Double element) {
                        return index % 3 == 0;
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.add( d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove(0).equals( list2.remove() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int r = (int) (Math.random() * list1.size());
                   Double element = list1.get( r );
                   int index = list1.lastIndexOf( element );
                   for( int i=list1.size()-1; i>=index; i-- )
                        list1.remove( i );
                   list2.removeRest( element );
              new Runnable() { public void run() {
                   list2.removeRest( Math.random() - 2 );
              new Runnable() { public void run() {
                   list1.clear();
                   list2.clear();
              new Runnable() { public void run() {
                   Collections.sort( list1 );
                   list2.sort();
              new Runnable() { public void run() {
                   Collections.sort( list1 );
                   Collections.reverse( list1 );
                   list2.sortDesc();
              new Runnable() { public void run() {
                   Comparator<Double> comparator = new Comparator<Double>() { public int compare(Double o1, Double o2) {
                        return o1.toString().substring(2).compareTo( o2.toString().substring(2) );
                   Collections.sort( list1, comparator );
                   list2.sort( comparator );
              new Runnable() { public void run() {
                   Comparator<Double> comparator = new Comparator<Double>() { public int compare(Double o1, Double o2) {
                        return o1.toString().substring(2).compareTo( o2.toString().substring(2) );
                   Collections.sort( list1, comparator );
                   Collections.reverse( list1 );
                   list2.sortDesc( comparator );
              new Runnable() { public void run() {
                   Double notExistElement = -2.0;
                   list2.removeAllEquals( notExistElement );
                   Tools.ensureEquals( list1, list2 );
                   list2.removeAllBetween( 0.5, 0.6 );
                   for( Iterator<Double> iter=list1.iterator(); iter.hasNext(); ) {
                        double d = iter.next();
                        if( d >= 0.5 && d < 0.6 )
                             iter.remove();
                   Tools.ensureEquals( list1, list2 );
         System.out.print( "test List2 " );
         for( int i=0; i < maxTestCount; i++ ) {
              tasks[ (int) (Math.random() * tasks.length) ].run();
              Tools.ensureEquals( list1, list2 );
              if( i % (maxTestCount/10) == 0 )
                   System.out.print( "." );
         System.out.println( " ok" );
    // source code : ListCondition
    public interface ListCondition<T> {
    boolean isConditionSatisfied( List2 list, int index, T element );

    Hi,
    I have the following statement:
    private List list = new ArrayList();
    why not use private ArrayList list = new
    ArrayList()?
    I know ArrayList implements List, so list has a wide
    scope, right? What's the benefit?
    Thanks,
    JieBy using the interface you are not tied to a specific implementation.
    Later, you may determine that using a LinkedList is more efficient to your specific code and then all you need to do is change the statement to:
    private List list = new LinkedList();As long as you are not casting the list reference to ArrayList (or something along those lines) you would not need to change anything else.

  • Linked List  - deleeting nodes - HELP!

    How do I delete all occurences of the nodes with the same parameters in the linked list ?
    example:
    Node1-> Node2 ->Node3->Node4->Node5
    Node1, Node4, and Node5 have the same String value, how do I delete them in one method without breaking the linked list ?
    thanks

    Hi,
    You have iterate thru the linked list remove one by one. Also have look at other collection classes like HashSet or HashMap for fast retrieval.

  • Adjacency List implementation of a graph

    Hey everyone,
    I'm starting to code a directed graph using an adjacency list and I'm running into a little trouble. I understand the concepts of the adjacency list structure, but I cant write seem to figure out how to code one. So far I'm using two doubly linked lists for storing the vertices and edges, and each is in its own class (I thought this would come in handy when later coding traversals in the graph). In the graph class, I'm thinking that an array list would work to store the adjacent vertices (each value in the array storing a list of vertices which are adjacent). However, if this is right then I'm not sure what to do with the edges, and how to make each edge know which vertices it is connecting.. In general, I'm looking for comments/advice on this type of graph implementation. Anything will help. Thanks a lot.

    import java.util.*;
    public class AdjacencyListNode
        private Set<Node> successors = new HashSet<Node>();
        public void addSuccessor(Node n) { ... }
        public boolean predecessorOf(Node n) { ... }
    }Of course, if you want multiple edges between nodes or weighted edges then it'll need modifying. You may also want to be able to apply a visitor to the successors.

  • Probem in printing the randum output from HashSet

    hi all,
    pls give me some hints to print only one randum out put..
    my code
    public static void main(String args[]) {
              HashSet set =new HashSet();
              set.add("Scambled egg");
              set.add("waffles");
              set.add("fruit");
              set.add("cereal");
              set.add("toast");
              set.add("yogart");
              Iterator itr = set.iterator ( );
              while(itr.hasNext()){
              String breakfast = itr.next().toString();

    i have done it..
    can you pls edit my code..
    ArrayList list = new ArrayList();
              list.add("Scambled egg");
              list.add("waffles");
              list.add("fruit");
              list.add("cereal");
              list.add("toast");
              list.add("yogart");

Maybe you are looking for