Hello,

I want to know how to return an entire object using API binary search. Not the index of where the object was found but the actual object. My WaketechFile class is just like the File class. Can anyone please help?

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.*;
/**
 * A class that represents a list of WaketechFile ojects as an ArrayList 
 */

/**
 * @author Noellie 
 *
 */
public class FileList 
{
    /*Instance Fields */
    public WaketechFile nuWKTFile;
    public ArrayList<WaketechFile> list;
    /* Constructor*/
    public FileList(File f )
    {
        nuWKTFile= new WaketechFile(f);
        list = new ArrayList<WaketechFile>();
        addFile(f);
    }
    /**
     * Add the Files objects to the ArrayLIst 
     * @param f file object passed as parameter 
     */
    public void addFile(File f)
    {
         list.add(new WaketechFile(f));
         if (f.isDirectory())
         {
             File [] files= f.listFiles();
             for (int i=0; i<files.length; i++)
             {
                 addFile(files[i]);
             }
         }
    }
    /**
     * Method that Searches the list files for match 
     */  
    public WaketechFile findLinear(String path)
    {
        //make it inot an obj
        //WaketechFile aWKTFile = new WaketechFile()
        for (WaketechFile i : list)
        {
            if(i.getPathName().equals(path))
            {
                return  i;
            }
        }    
        return null;    
    }
    /**
     * Sort the Array List using API sort 
     *
     */
    public  void sort()
    {
        Collections.sort(list);
    }
/**
 * Method that Searches the list files for match 
 * using the Java Api Collection and after the Sort method
 */  
    public WaketechFile findBinary(String path)
    {
        //WaketechFile otherFile= new WaketechFile(path);
        sort();
        for(WaketechFile i: list)
        {
             int loc = Collections.BinarySearch(list, path); 
             return i;//    COLOR="red"]Help????????????[[/COLOR]   
                               }
    }
}

Edited 4 Years Ago by diafol: fixed formatting

Collections.BinarySearch returns the index in the list where the item was found. If you need to return the object then return list.get(index) . Your foreach loop around the search call doesn't make much sense though. For a given path, it's a single call to locate it within the list. Also, sorting the list for each search is unnecessary - just sort it when the list changes (using a sorted set would manage that for you automatically)

This article has been dead for over six months. Start a new discussion instead.