Results 1 to 2 of 2
  1. #1
    newtojava7 is offline Member
    Join Date
    Jan 2008
    Posts
    16
    Rep Power
    0

    Default recursively searching through arraylists

    hello,

    i have a bunch of strings in an arraylist, which im displaying in a JList. i have a textfield with a search button which allows the user to type in a string into the textfield and search for that string within the arraylist. i need this search to be done recursively, how can I do this? thanks.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    import java.util.*;
    import java.util.List;
    
    public class SearchingTest {
        static String[] items = {
            "London", "Manchester", "Cardiff", "Bristol"
        };
        static List<String> list = Arrays.asList(items);
    
        public static void main(String[] args) {
            String s = //items[2];
                       "Middlesex";
            int index = search(s, 0);
            String result = (index == -1) ? "not found"
                                          : "found at index " + index;
            System.out.println(s + " is " + result);
        }
    
        private static int search(String target, int n) {
            if(n > list.size()-1)
                return -1;
            if(list.get(n).equals(target))
                return n;
            else
                return search(target, n+1);
        }
    }

Similar Threads

  1. A Map implemented with ArrayLists
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-16-2008, 10:29 PM
  2. arraylists problem
    By newtojava7 in forum New To Java
    Replies: 1
    Last Post: 03-12-2008, 07:38 AM
  3. Computing Fibonacci numbers recursively
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-22-2008, 08:20 PM
  4. searching
    By nalinda in forum New To Java
    Replies: 3
    Last Post: 12-06-2007, 02:56 AM
  5. Replies: 2
    Last Post: 11-27-2007, 01:45 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •