Using Collections.binarySearch on a Linked list

hi all
i want to use the Collections.binarySearch method on a linked list object to add items to it. These items are of type Entry (a class i have created).
i have the following code:
public void addEntry(Entry newEntry)
        int pos = Collections.binarySearch(entryList, newEntry);
        if (pos < 0)
            entryList.add(-(pos) -1, newEntry);
[\CODE]
where entryList is declared as:
private List entryList = new LinkedList();
This code compiles OK, but when i run it to add an Entry element to the linked list, i get a ClassCastException being thrown, and im not sure why.
i can add one Entry object to the list ok, but it falls over when i try to add another. im trying to order my Entry objects by a field called 'surname', so the binarySearch finds the correct location in the list for the new entry and then it is added.
any help on this would be appreciated
cheers
david                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

binarySearch doesn't work on a linked listSo untrue:Well, only mostly untrue. It still doesn't really do a binary search on your linked list
From the javadoc
'This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access). If the specified list does not implement the RandomAccess and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons. '
import java.util.*;
public class Test {
public static void main(String[] args) {
List entryList = new LinkedList();
entryList.add(new Integer(3));
entryList.add(new Integer(5));
entryList.add(new Integer(1));
Collections.sort(entryList);
System.out.println(Collections.binarySearch(entryList,
new Integer(5)));
}Compiles and runs without any problems

Similar Messages

  • N^2 log(n) for Collections.sort() on a linked list in place?

    So, I was looking over the Java API regarding Collections.sort() on linked lists, and it says it dumps linked lists into an array so that it can call merge sort. Because, otherwise, sorting a linked list in place would lead to a complexity of O(n^2 log n) ... can someone explain how this happens?

    corlettk wrote:
    uj,
    ... there are other sorting methods for linked lists with an O(N*N) complexity.Please, what are those algorithms? I'm guesing they're variants off insertion sort, coz an insertion is O(1) in a linked list [and expensive in array]... Am I warm?You don't have to change the structure of a linked list to sort it. You can use an ordinary Bubblesort. (The list is repeatedly scanned. In each scan adjacent elements are compared and if they're in wrong order they're swapped. When one scan of the list passes without any swaps the list is sorted). This is an O(N*N) algoritm.
    What I mean is it's possible to sort a list with O(N*N) complexity. It doesn't have to be O(N*N*logN) as the Java documentation kind of suggests. In fact I wouldn't be surprised if there were special O(N*logN) algoritms available also for lists but I don't know really. In any case Java uses none of them.

  • Comparable linked list sorting

    i have been trying to find a way to sort a link listed. After some reading i found out that it is probably best to use collections.sort(list). I think i understand how to implement it , i need to declare a compareto and equals method. However, most of the reading i have done shows how to create a collection from a linked list and add items to the collection and sort them, however it doesn show how to copy this sorted collection back inot a linked list. I need to remove items and add items to the sorted linked list. Is it possible to create a linked list, sort it using the collection sort and return the sorted linked list? I have looked in the api's but got confused!!

    You don't need to copy anything.
    List list = new LinkedList(); // or ArrayList
    // list.add stuff
    Collections.sort(list); Assuming whatever you added to the list implements Comarable, the list is now sorted.

  • Linked Lists

    I am trying to create a linked list with an object called ClassID But I am confused on the constructor. Could someone point me in teh right direction. this is what i got:
    import java.io.*
    public class Link
         public ClassID id;
         public Link next;
    public Link(ClassID id)
         id = new ClassID(id);
         

    Sorry, after rereading your initial post a third time, I see there is more to what you are asking and displaying than is easily discernable.
    I am assuming you mant the linked list wis of type ClassId, if ClassId was actually meant to be the data objects stored in the list then you must give your Linked List a new name, so say ClassLl. If this is the case replace ClassId with ClassLl in my example below.
    First, when you are using a constructor you don't really want to pass in "id"s and you definitely don't need "next". This is because the purpose of the constructor is to build a new linked list, and id and next should never be used in making a new linked list. The ClassId object if you have to create your own linked list without using the collections libraries should have a id and next field, but they should not be necessary for the constructor. The id, next, and ClassId if it is meant to be the data stored all should only come into play in methods manipulating the linked list.
    At most, you may have an already cronstructed linked list that you plan to pass to the linked list, but there is never a reason to pass id or next to a constructor.
    so
    public class List
         public ClassID id = new ClassId(); //or = new LinkedList() if allowed
            public List()  //there is no preexisting linkedlist being passed in
         public List(ClassID inID)  //inId is a linkedlist
              id = inID;
    }In short, worry about setting up your linked list before you start trying to fill it with stuff.

  • Display a Linked List ADT in JTree ?

    Most of the Swing examples that I have noticed for building a JTree have used many different ADTs, but I haven't noticed any examples to use a JTree to display a linked list (not necessarily the LinkedList class though). I was studying Data Structures & Algorithms, and the majority of the examples for Binary Trees, Red-Black Trees, and 2-3-4 Trees use a form of a linked list to connect all of the nodes together.
    Isn't it, or should it, be possible to use a JTree to display a linked list ADT ? Or am I missing something somewhere ?

    Maybe, if you only had a reference to one other node in the object that is being linked together.
    What if there was a node object that contained three references ?
    nextNode
    prevNode
    subNode

  • How to use methods when objects stored in a linked list?

    Hi friend:
    I stored a series of objects of certain class inside a linked list. When I get one of them out of the list, I want to use the instance method associated with this object. However, the complier only allow me to treat this object as general object, ( of Object Class), as a result I can't use instance methods which are associated with this object. Can someone tell me how to use the methods associated with the objects which are stored inside a linked list?
    Here is my code:
    import java.util.*;
    public class QueueW
         LinkedList qList;
         public QueueW(Collection s) //Constructor of QuequW Class
              qList = new LinkedList(s); //Declare an object linked list
         public void addWaiting(WaitingList w)
         boolean result = qList.isEmpty(); //true if list contains no elements
              if (result)
              qList.addFirst(w);
              else
              qList.add(w);
         public int printCid()
         Object d = qList.getFirst(); // the complier doesn't allow me to treat d as a object of waitingList class
              int n = d.getCid(); // so I use "Object d"
         return n; // yet object can't use getCid() method, so I got error in "int n = d.getCid()"
         public void removeWaiting(WaitingList w)
         qList.removeFirst();
    class WaitingList
    int cusmNo;
    String cusmName;
    int cid;
    private static int id_count = 0;
         /* constructor */
         public WaitingList(int c, String cN)
         cusmNo = c;
         cusmName = cN;
         cid = ++id_count;
         public int getCid() //this is the method I want to use
         return cid;

    Use casting. In other words, cat the object taken from the collection to the correct type and call your method.
       HashMap map = /* ... */;
       map.put(someKey, myObject);
       ((MyClass)(map.get(someKey)).myMethod();Chuck

  • How to add SharePoint 2013 Promoted link list view web part in page programatically with Tiles view using CSOM.

    How to add SharePoint 2013 Promoted link list view web part in page programatically with Tiles view using CSOM. I found that it can be
    done by using XsltListViewWebPart class but how can I use this one by using shraepoint client api.
    shiv

    Nice, can you point me to the solution please ?
    I'm  trying to do this but I get an error : 
    Web Part Error: Cannot complete this action. Please try again. Correlation ID: blablabla
    StackTrace:    at Microsoft.SharePoint.SPViewCollection.EnsureViewSchema(Boolean fullBlownSchema, Boolean bNeedInitallViews)     at Microsoft.SharePoint.SPList.GetView(Guid viewGuid)   
    All help really appreciated.

  • Recursion using a linked list

    I am confused at how to make a linked list using recursion. I've been looking at the syntax and examples from the web for the past couple hours, but all seem to be based on an empty .java file. I need to put it in my code somehow. here's the code segment:
    public static boolean RecursiveTest (String s, int start, Node n) {
    // The linked list
    Node<char> bracket = new Node<char>();
    int size = s.length();
    char v = s.charAt(start);
    //String sElement = parens.top();
    boolean isGood = true;
    // ending "ifs"
    if (size == 0) { System.out.println("empty string");  return false; }
    if (start == size) return isGood;
    if (s.charAt(start) == '(' || s.charAt(start) == '[' ||
              s.charAt(start)== '{') {
    v.Push(sChar);
    System.out.println(sChar);
    return RecursiveTest(start+1, s.charAt(start));
    else if (sChar.equals(")") && sElement.equals("(")) {
    parens.Pop();
    System.out.println(sChar);
    return RecursiveTest(start+1);
    else if (sChar.equals("]") && sElement.equals("[")) {
    parens.Pop();
    System.out.println(sChar);
    return RecursiveTest(start+1);
    else if (sChar.equals("}") && sElement.equals("{")) {
    parens.Pop();
    System.out.println(sChar);
    return RecursiveTest(start+1);
    else if (sChar.equals(")") && !sElement.equals("(")) {
    System.out.println("bad");
    isGood = false;
    return isGood;
    else if (sChar.equals("]") && !sElement.equals("[")) {
    System.out.println("bad");
    isGood = false;
    return isGood;
    else if (sChar.equals("}") && !sElement.equals("{")) {
    System.out.println("bad");
    isGood = false;
    return isGood;
    else return RecursiveTest(start+1);
    } // end of RecursiveTest
    I'm passing a string, 0, and a new node (i dunno about the last one there), from an above main class.
    This code is wrong, i know, but it's all I got done so far. How would I be able to make a linked list inside this method?

    No one knows how to do a linked list inside a recursive method?Yes we do, but you have to realize that a list (whether it be a linked list
    or an array list or whatever) has nothing to do with recursion per se.
    If that list has to keep track of some state it certainly mustn't be created
    within that recursive method as a local variable. And (see my previous
    reply), what do you need recursion for? Counting and pairing brackets
    can easily be done using an iterative method where the list keeps track
    of the last seen left bracket (of any type).
    kind regards,
    Jos

  • How to write from a linked list collection to a text file.

    Hi,
    I want to write my data in linked list collection to a text file.
    the following is the code of my linked list. how do i write it
    Iwant the data to be comma separated while writing it to a text file.
    please help.
    class MailList
            public static void main(String args[])
                    LinkedList m1 = new LinkedList();
                    m1.add(new Address("J.W.West", "11 Oak Ave",
                           "Urbana", "IL", "118011"));
                    m1.add(new Address("H.S.sandy", "1 k ve",
                           "Bana", "L", "18011"));
                    m1.add(new Address("K.Satish", "1 104 Clarence Street",
                            "Strathfield", "NSW", "135"));
                    Collections.sort(m1);
                    Iterator itr = m1.iterator();
                    while(itr.hasNext())
                            Object element = itr.next();
                            System.out.println(element + "\n");
    }

    look at the API for FileWriter.
    http://java.sun.com/docs/books/tutorial/essential/io/index.html

  • How to use circular linked list in pl/sql?

    Hi all,
    how to use the circular linked list on pl/sql programming.
    thanks in advance
    Rgds,
    B@L@

    d balamurugan wrote:
    Hi,
    I needed this concept for the below example
    TABLE_A have the columns of
    ID COL_1 COL_2 COL_3 COL_4 COL_5 COL_6 COL_7
    1....Y.........N........N.........Y........ N........N........ N
    2....N.........N....... N.........Y.........N........N.........Y
    in the above data
    for id 1 i will need to take the value for COL_4, then i will check the next availability of Y through out through out the remaining columns, so next availability is on COL_1 so, i need to consider COL_4 which already Y and also i need to consider COL_5, COL_6, COL_7 as Y.
    for id 2 if i need COL_7 then i need to come back on circular way and need to check the next availability of Y and need to take the columns having N before the next availability of YAnd... even after all that description... you haven't given any indication of what the output should look like.
    Taking a wild guess on my part... something like this would do what you appear to be asking...
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 1 as id, 'Y' as col1, 'N' as col2, 'N' as col3, 'Y' as col4, 'N' as col5, 'N' as col6,'N' as col7 from dual union all
      2             select 2, 'N', 'N', 'N', 'Y', 'N', 'N', 'Y' from dual)
      3  --
      4  -- END OF TEST DATA
      5  --
      6  select id
      7        ,rcol
      8        ,case when instr(cols,'Y',rcol+1) = 0 then instr(cols,'Y')
      9              else instr(cols,'Y',rcol+1)
    10         end as next_Y_col
    11  from   (select id, rcol, col1||col2||col3||col4||col5||col6||col7 as cols
    12          from t, (select &required_col as rcol from dual)
    13          where id = &required_id
    14*        )
    SQL> /
    Enter value for required_col: 4
    old  12:         from t, (select &required_col as rcol from dual)
    new  12:         from t, (select 4 as rcol from dual)
    Enter value for required_id: 1
    old  13:         where id = &required_id
    new  13:         where id = 1
            ID       RCOL NEXT_Y_COL
             1          4          1
    SQL> /
    Enter value for required_col: 7
    old  12:         from t, (select &required_col as rcol from dual)
    new  12:         from t, (select 7 as rcol from dual)
    Enter value for required_id: 2
    old  13:         where id = &required_id
    new  13:         where id = 2
            ID       RCOL NEXT_Y_COL
             2          7          4
    SQL>If that's not what you want... then it's time you started learning how to ask questions properly.

  • Trouble importing third party classes & using linked list in j2me

    Hi!
    I need to use the linked list data structure in a j2me application im developing. Al long as I know, it is not included in standard libraries.
    I found the "workaround", the substitution in Jade Laepaddon. This is actually a set of classes in a directory.
    I know this is extremely dumb, but I have no luck impotring these classes in my project.
    Im using the WTK2.0 to compile and execute the application, but I don't have an Idea how to add a directory in the CLASSPATH.
    So, the actual question should be: how to include a directory of files, so that it can be imported with:
    import dirName.*;
    Thanks!

    Tha import problem is solved, but I'm still not able to use the LinkedList class. In the jade/util/leap there is a LinkedList.java file, but I get an error :
    /home/mile/WTK2.0/apps/myGame/tmplib/jade.jar(jade/util/leap/LinkedList.java):48: class LinkedList is public, should be declared in a file named LinkedList.java
    (source unavailable)
    /home/mile/WTK2.0/apps/myGame/tmplib/jade.jar(jade/util/leap/LinkedList.java):48: cannot resolve symbol
    symbol : class List
    location: class jade.util.leap.LinkedList
    (source unavailable)
    /home/mile/WTK2.0/apps/myGame/tmplib/jade.jar(jade/util/leap/LinkedList.java):48: cannot resolve symbol
    symbol : class Serializable
    location: class jade.util.leap.LinkedList
    (source unavailable)
    /home/mile/WTK2.0/apps/myGame/tmplib/jade.jar(jade/util/leap/Iterator.java):41: class Iterator is public, should be declared in a file named Iterator.java
    (source unavailable)
    when initialising an LinkedList type object.

  • Why LinkedList uses doubly linked list and not single link list

    Hi,
    Please help me to understand the concept behind java using doubly linked list for LinkedList and not single link list?
    Edited by: user4933866 on Jun 26, 2012 11:22 AM
    Edited by: user4933866 on Jun 26, 2012 11:25 AM
    Edited by: EJP on 27/06/2012 08:50: corrected title to agree with question

    EJP wrote:
    Could you help me with one real world use case where we need to traverse linklist and arraylist in backward direction other than printing the linklist or arraylist in reverse order. One example is that you might want to use it as a stack. For a very large (+very+ large) stack it would out-perform the Vector-based Stack in the API.The first thing that pops into my head is an undo/redo function for a text editor. Each edit action is dumped onto such a stack. Each time you hit CTRL+Z to undo an action you go back in the stack. Each time you hit CTRL+Y to redo the action you go forward again.

  • Implementing TRIE using linked lists

    Node InsertNode(string name, Node root)
    int index = 1;
    string key;
    Node currentNode = root;
    while (index <= name.Length)
    key = name[index - 1].ToString();
    Node resultNode = currentNode.Children.GetNodeByKey(key);
    if (resultNode == null)
    Node newNode = new Node(key, name.Substring(0, index));
    if (index == name.Length)
    newNode.IsTerminal = true;
    currentNode.Children.Add(newNode);
    currentNode = newNode;
    else
    currentNode = resultNode;
    index++;
    return root;
    i want to use linked lists. i dont no what nodes are.like basically how do i use linked lists in the place of nodes in this code?
    thanx

    http://www.codeproject.com/KB/recipes/PhoneDirectory.aspx?display=Print <= code tags?
    coherent questions?
    class LinkedListNode {
    private LinkedListNode next;
    private Object data;
    public void insertAfter(Object data) {
    LinkedListNode newNode = new LinkedListNode();
    newNode.data = data;
    newNode.next = next;
    this.next = newNode;
    this is ur typical insert method for a linkedlistnode. you're saying nodes do the dirty work. how do connect this code with the one i posted in my previous msg? where do i get NODE from. What is this class.

  • Linked list to string coercion doesn't use text item delimiters: bug?

    set AppleScript's text item delimiters to {"; "} -- well-known technique
    {1, -1, "c", "d"} as string -- curly braces specify a vector, delimiters work
    -- result: "1; -1; c; d"
    {1, -1, "c", "d"} as linked list as string -- if coerced to linked list, delimiters ignored
    -- result: "1-1cd"
    [1, -1, "c", "d"] as string -- square brackets specify a linked list, delimiters ignored
    -- result: "1-1cd"
    [1, -1, "c", "d"] as vector as string -- coercing linked list to vector first works
    -- result: "1; -1; c; d"

    Hello
    It appears that linked list to string coercion does not respect the AppleScript's text item delimiters which are set to list of Unicode text. (Unicode TIDs have no effects in coercion as if it were set to {""})
    I can confirm this behaviour in both AppleScript 1.8.3 (OS9) and 1.9.1 (OSX10.2.8) at hand.
    So it has been as such for a long time. Bug I'd call it.
    By the way, although this is not the point, linked list is a historical residue and of little use in real scripting. After all, it is much slower than vector with appropriate coding. So we may always coerce it to vector without losing anything.
    Regards,
    H
    Linked list to string coercion & AppleScript's text item delimiters (TIDs).
    When AppleScript's TIDs are set to list of Unicode text,
    the TIDs have no effect in coercion from linked list to string as if they were set to {""}.
    set aa to [1, 2, "a", "b"]
    --set aa to {1, 2, "a", "b"} as linked list
    set t1 to list2text(aa, ";") -- "1;2;a;b" -- in pre-AppleScript 2.0
    set t2 to list2text(aa, ";" as Unicode text) --"12ab"
    return {t1, t2}
    on list2text(aa, delim)
    list aa : source list
    string delim : a text item delimiter
    return string
    local astid, astid0, t
    set astid to a reference to AppleScript's text item delimiters
    set astid0 to astid's contents
    try
    set astid's contents to {delim}
    --set t to aa as string
    --set t to aa as Unicode text
    set t to "" & aa
    set astid's contents to astid0
    on error errs number errn
    set astid's contents to astid0
    error errs number errn
    end try
    return t
    end list2text

  • I am unable using the properties inline to bring my link list to a horizontal look?

    I cannot in dreamweaver site set up bring my link list from a vertical to a horizontal using the properties inline?

    And that is supposed to mean what? If you refer to an alignment option for CSS, then you ahve a severe misunderstanding of what "inline" means. No, it doesn't mean "in a line". Time to read up...
    Mylenium

Maybe you are looking for

  • Expdp export error

    Please help if you can. We have oracle running on a Windows XP machine and another instance running on a Windows 2003 server machine. I get the same results when I try to run the export on either database. I connected to Oracle with SQLPlus and sent

  • Unable to load LabVIEW RT from drive

    Trying to boot RT on PXI-8187 controller with original setup, what ever RT boot selection is used either hardware switch or BIOS RT boot option, the terminal will show the following: Unable to load LabVIEW RT from drive! Booting safe mode from ROM...

  • Profile LIMIT=DEFAULT ?

    I'm using profiles in the database to prevent to much sessions per user. I have the next situation 1 select resource_name,limit 2 from dba_profiles 3 where profile = 'NEW_PROFILE' 4* order by 1,2 SQL> / RESOURCE_NAME LIMIT COMPOSITE_LIMIT DEFAULT CON

  • The serial number is invalid what next?

    how do i get Adobe to recognized the serial number?  This is my second disc ordered from Amazon.  Who is at fault?

  • Software update fails for me, please help

    Hello, I am running 10.6.7 on a 2.8GHz  MacBook Pro. I am having difficulties getting software update to load the newest updates for iTunes 10.3.1 and AirPort Utility 5.5.3. When I run the update gui I get the following error: It downloads the reques