Implementing Lists

I am at the point where I have had two Java courses and am now ready to learn data structures. I have a book and it is ok, but it does not show you any implementation of the data structrues. Right now I am starting with the most basic data structure which is Lists and i understand how they work (array based, Linked-List and Double-Linked-Lists) however the book shows no implementation of them in "main". If someone could point me to some resources that show these implementations, I would greatly appreciate it.

Have a look in the src.zip file which comes with your JDK. It has the source for 90+% of the Java APIs including List, LinkedList, ArrayList, CopyOnWriteArrayList.
You can also find copies of the source posted on the web.

Similar Messages

  • How to implement list of values with bind parameters

    Hi All,
    Please give me details about how to implement list of values with bind parameters.
    I have implemented with below things.
    1) created lov view object with query like select meaning, lookup_code from fnd_lookup_values where lookup_type=:1;
    2) The above vo added to applicationa module.
    3) created Controller class in the co class written code in processRequest();
    String vLookupType=pageContext.getParameter("LookupType");
    Serializable params={vLookupType};
    am.invokemethod("Initialize",params);
    4) In AM Impl Class invoke the VO
    5) In VO Impl class executed the query..
    But the above process working fine but when i give the value in lov text field like 'C' then press tab button the result will not showing instead of that i am getting error message, i want to implement standard lov functionality while implementing query with bind parameter.
    any thing reqired to add the code to controller for search criteria..
    Thanks
    Mateti

    Hi
    i am getting error as
    oracle.apps.fnd.framework.OAException: oracle.jbo.SQLStmtException: JBO-27122: SQL error during statement preparation. Statement: SELECT * FROM (SELECT meaning, lookup_code,lookup_type
    FROM fnd_lookup_values
    WHERE view_application_id = 200) QRSLT WHERE (lookup_type=:1 AND ( UPPER(MEANING) like :2 AND (MEANING like :3 OR MEANING like :4 OR MEANING like :5 OR MEANING like :6)))
    Thanks
    Mateti

  • Why does ArrayList "implement" List, when it extends AbstractList?

    I never noticed this before, and so i was wondering if there's a good explanation for it: If you look at how ArrayList is defined, you'll see this:
    ===
    public class ArrayList
    extends AbstractList
    implements List, RandomAccess, Cloneable, Serializable
    ===
    But AbstractList, which ArrayList extends, already implements List, like this:
    ===
    public abstract class AbstractList
    extends AbstractCollection
    implements List
    ===
    So, why does ArrayList list List in the list of implements? (that's kind of a confusing sentence, read it twice) By extending AbstractList, it's already clear that it implements List - now it's like it's implementing it twice (which doesn't hurt of course, but it doesn't help either.) This seems inconsistent with other parts of the API, where usually in cases like this (with an abstract class being extended) the interface isn't listed again in the final concrete class. For instance:
    public class TitledBorder
    extends AbstractBorder
    and:
    public abstract class AbstractBorder
    extends Object
    implements Border, Serializable
    but:
    TiledBorder doesn't mention Border in its (non-existent) list of implements.
    Any ideas?
    -- Niek

    Surely enough the AbstractList
    takes care of all the burden (like I wrote before),
    but the ArrayList (re)implements the List interface
    for
    very sound reasons. If it didn't, the
    o.getClass().getInterfaces() would've missed the List
    interface,Since AbstractList implements List, ArrayList has an implicit "implements List." However, as you say, getInterfaces() doesn't produce that.
    So you're saying that the VM has to do something different to find the method? I don't think so. The compiler may have to work harder, but in both cases, the VM does an invokeinterface. The javap output looks the same in a copule of test classes I created.
    public interface I1 {
        public void i1Meth();
        public void i1Meth2();
    public abstract class IA implements I1 {
        public void i1Meth() {}
    public class IC1 extends IA implements I1 {
        public void i1Meth2() {}
        void dummy() {
            I1 i1 = new IC1();
            i1.i1Meth();
            i1.i1Meth2();
    import java.util.*;
    public class IC2 extends IA {
        public void i1Meth2() {}
        void dummy() {
            I1 i1= new IC2();
            i1.i1Meth();
            i1.i1Meth2();
        public static void main(String[] args) {
            System.out.println(Arrays.asList(IC2.class.getInterfaces()));
            System.out.println(Arrays.asList(IC1.class.getInterfaces()));
    Compiled from "IC1.java"
    public class IC1 extends IA implements I1{
    void dummy();
      Code:
       0:   new     #2; //class IC1
       3:   dup
       4:   invokespecial   #3; //Method "<init>":()V
       7:   astore_1
       8:   aload_1
       9:   invokeinterface #4,  1; //InterfaceMethod I1.i1Meth:()V
       14:  aload_1
       15:  invokeinterface #5,  1; //InterfaceMethod I1.i1Meth2:()V
       20:  return
    Compiled from "IC2.java"
    public class IC2 extends IA{
    void dummy();
      Code:
       0:   new     #7; //class IC2
       3:   dup
       4:   invokespecial   #8; //Method "<init>":()V
       7:   astore_1
       8:   aload_1
       9:   invokeinterface #9,  1; //InterfaceMethod I1.i1Meth:()V
       14:  aload_1
       15:  invokeinterface #10,  1; //InterfaceMethod I1.i1Meth2:()V
       20:  return
    ...

  • Why does  ArrayList implement List when extending AbstractList

    Hi
    I am unable to understand why would the ArrayList class implement the List interface, when it is already extending the AbstarctList class. If anyone can explain, it would be a great help.

    Why does ArrayList implement List when extendingAbstractList
    It is a question of style. ArrayList'simplementing
    List is a crucial piece of information, whereasits
    extending AbstractList is a kind of implementation
    detail. If would not matter much to the user if it
    did not extend AbstractList but implemented List
    directly.So why don't those subclasses of ArrayList step up
    and implement List again? I agree, extending
    ArrayList is an implementation detail, and in fact
    perhaps they should have made ArrayList a field
    rather than a superclass...Because those subclasses job is not to be a List but to be an extension of ArrayList. In general if you wanted to be a List you would be extending AbstractList. You don't just implement List because you happen to have the right methods, you implement List because you feel being a List is part of that classes main behavior.
    Its a suttle point but I feel its more than a matter of style. Its a matter of correctness.
    Also, ArrayList could use composition by having an AbstractList member within itself. In this case it would implement List as well and achieve the same result. Letting users know it intends to fill the role of a List.

  • A java List that implements the Stream interface?

    Hello,
    I just took some time to start looking into the java-8 buzz about streams and lambdas.
    And have a couple of questions...
    The first thing that surprised me is that you cannot apply the streams operations,
    like .map(), .filter() directly on a java.util.List.
    First question:
    Is there a technical reason why the java.util.List interface was not extended with
    default-implementations of these streams operations? (I guess there is...?)
    Googling a bit, I see lots of examples of people coding along the pattern of:
        List<String> list = someExpression;
        List<String> anotherList = list.stream().map(x -> f(x)).collect(Collectors.toList());
    which becomes very clumsy, if you have a lot of these stream-operations in your code.
    Since .stream() and .collect() are completely irrelevant to what you want to express,
    you would rather like to say:
        List<String> list = someExpression;
        List<String> anotherList = list.map(x -> f(x));
    What I first did as a workaround, was to implement (see code below)
    a utility interface FList, and a utility class FArrayList (extending ArrayList with .map() and .filter()).
    (The "F" prefixes stand for "functional")
    Using these utilities, you now have two options to create less clumsy code:
        List<String> list = someExpression;
        List<String> anotherList = FList.map(list, x -> f(x));
        List<String> thirdList = FList.filter(list, somePredicate);
    or better:
        FList<String> list = new FArrayList<String>(someExpression);
        FList<String> anotherList = list.map(x -> someFunction(x));
        FList<String> thirdList = list.filter(somePredicate);
    My second question:
    What I would really like to do is to have FArrayList implement the
      java.util.stream.Stream interface, to fully support the java-8 functional model.
    Since that involves implementing some 40 different methods, I would just like to know,
    if you know somebody has already done this kind of work, and the code is
    available somewhere as a public jar-file or open-source?
        public interface FList<T> extends List<T> {
            public static <A, B> List<B> map(List<A> list, Function<A, B> f) {
                return list.stream().map(f).collect(Collectors.toList());
            public static <A> List<A> filter(List<A> list, Predicate<A> f) {
                return list.stream().filter(f).collect(Collectors.toList());
            default <R> FList<R> map(Function<T, R> f) {
                FList<R> result = new FArrayList<R>();
                for (T item : this) {
                    result.add(f.apply(item));
                return result;
            default FList<T> filter(Predicate<T> p) {
                FList<T> result = new FArrayList<T>();
                for (T item : this) {
                    if (p.test(item)) {
                        result.add(item);
                return result;
        public class FArrayList<T> extends ArrayList<T> implements List<T>, FList<T> {
            private static final long serialVersionUID = 1L;
            public FArrayList() {
                super();
            public FArrayList(List<T> list) {
                super();
                this.addAll(list);

    I believe SSH and telnet are used for interactive command line sessions, don't know how you want to use them in a program.

  • Why the ArrayList implements the List interface

    Why the ArrayList implements the List interface even though it extends the AbstractList class. Is it only for clarity of interface implemented?

    899440 wrote:
    Why the ArrayList implements the List interface even though it extends the AbstractList class. Is it only for clarity of interface implemented?I dont think there's any specific reason for that. In my opinion its redundant. May be its added for clarity so that from the documentation its obivous that ArrayList implements List.
    May be there's something which I am missing regarding this?

  • What are the thread safety requirements for container implementation?

    I rarely see in the TopLink documentation reference to thread safety requirements and it’s not different for container implementation.
    The default TopLink implementation for:
    - List is Vector
    - Set is HashSet
    - Collection is Vector
    - Map is HashMap
    Half of them are thread safe implementations List/Collection and the other half is not thread safe Set/Map.
    So if I choose my own implementation do I need a thread safe implementation for?
    - List ?
    - Set ?
    - Collection ?
    - Map ?
    Our application is always reading and writing via UOW. So if TopLink synchronize update on client session objects we should be safe with not thread safe implementation for any type; does TopLink synchronize update on client session objects?
    The only thing we are certain is that it is not thread safe to read client session object or read read-only UOW object if they are ever expired or ever refreshed.
    We got stack dump below in an application always reading and writing objects from UOW, so we believe that TopLink doesn’t synchronize correctly when it’s updating the client session objects.
    java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449)
    at java.util.AbstractList$Itr.next(AbstractList.java:420)
    at oracle.toplink.internal.queryframework.InterfaceContainerPolicy.next(InterfaceContainerPolicy.java:149)
    at oracle.toplink.internal.queryframework.ContainerPolicy.next(ContainerPolicy.java:460)
    at oracle.toplink.internal.helper.WriteLockManager.traverseRelatedLocks(WriteLockManager.java:140)
    at oracle.toplink.internal.helper.WriteLockManager.acquireLockAndRelatedLocks(WriteLockManager.java:116)
    at oracle.toplink.internal.helper.WriteLockManager.checkAndLockObject(WriteLockManager.java:349)
    at oracle.toplink.internal.helper.WriteLockManager.traverseRelatedLocks(WriteLockManager.java:144)
    at oracle.toplink.internal.helper.WriteLockManager.acquireLockAndRelatedLocks(WriteLockManager.java:116)
    at oracle.toplink.internal.helper.WriteLockManager.checkAndLockObject(WriteLockManager.java:349)
    at oracle.toplink.internal.helper.WriteLockManager.traverseRelatedLocks(WriteLockManager.java:144)
    at oracle.toplink.internal.helper.WriteLockManager.acquireLockAndRelatedLocks(WriteLockManager.java:116)
    at oracle.toplink.internal.helper.WriteLockManager.acquireLocksForClone(WriteLockManager.java:56)
    at oracle.toplink.publicinterface.UnitOfWork.cloneAndRegisterObject(UnitOfWork.java:756)
    at oracle.toplink.publicinterface.UnitOfWork.cloneAndRegisterObject(UnitOfWork.java:714)
    at oracle.toplink.internal.sessions.UnitOfWorkIdentityMapAccessor.getAndCloneCacheKeyFromParent(UnitOfWorkIdentityMapAccessor.java:153)
    at oracle.toplink.internal.sessions.UnitOfWorkIdentityMapAccessor.getFromIdentityMap(UnitOfWorkIdentityMapAccessor.java:99)
    at oracle.toplink.internal.sessions.IdentityMapAccessor.getFromIdentityMap(IdentityMapAccessor.java:265)
    at oracle.toplink.publicinterface.UnitOfWork.registerExistingObject(UnitOfWork.java:3543)
    at oracle.toplink.publicinterface.UnitOfWork.registerExistingObject(UnitOfWork.java:3503)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.registerIndividualResult(ObjectLevelReadQuery.java:1812)
    at oracle.toplink.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneNormally(ObjectBuilder.java:455)
    at oracle.toplink.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:419)
    at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:379)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:455)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.conformIndividualResult(ObjectLevelReadQuery.java:622)
    at oracle.toplink.queryframework.ReadObjectQuery.conformResult(ReadObjectQuery.java:339)
    at oracle.toplink.queryframework.ReadObjectQuery.registerResultInUnitOfWork(ReadObjectQuery.java:604)
    at oracle.toplink.queryframework.ReadObjectQuery.executeObjectLevelReadQuery(ReadObjectQuery.java:421)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:811)
    at oracle.toplink.queryframework.DatabaseQuery.execute(DatabaseQuery.java:620)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:779)
    at oracle.toplink.queryframework.ReadObjectQuery.execute(ReadObjectQuery.java:388)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:836)
    at oracle.toplink.publicinterface.UnitOfWork.internalExecuteQuery(UnitOfWork.java:2604)
    at oracle.toplink.publicinterface.Session.executeQuery(Session.java:993)
    at oracle.toplink.publicinterface.Session.executeQuery(Session.java:950)

    Hi Lionel,
    As a general rule of thumb, the ATI Rage 128 Pro will not support a 20" LCD. That being said, there are reports of it doing just that (possibly the edition that went into the cube).
    I'm not that familiar with the ins and outs of the Cube, so I can't give you authoritative information on it.
    A good place to start looking for answers is:
    http://cubeowner.com/kbase_2/
    Cheers!
    Karl

  • (Data Structures) Position (in Lists) ...simple - Urgent help needed!!!

    I know that Position is the abstract data type and that it supports only one method - element() (that returns the element stored in this position).. Now when I wish to implement a List (with doubly linked list) using the Interface List...In the Interface List there are quite few methods to implement , however, few of them require Position parameter...And this is where I am getting confused..What is the Position parameter? A number? or? Here is a sample code
    //Node class for implementing a Doubly linked list
    Class DoublyNode implements Position
    { public DoublyNode prev, next;
    public Object element
    //constructor
    public Dnode()
    { prev = null
    next = null
    element = null
    public Object element(){
    return element;
    Class NodeList implements List{
    // bunch of methods and variables
    public Position before(Position p) // What is Position parameter? a position number? or what?
    { DoublyNode v = (DoublyNode)p;
    DoublyNode prev = v.prev;
    return prev;
    Now I know since DoublyNode implements Position, we can cast a position to a node, but what is that Position parameter? Can anybody explain this minor detail to me? Or how do these Position parameters work in programing? All I know is, given a position parameter (what ?) the Doubly linked list will instantly locate the appropriate node (how) and you can cast it to a node and return the node...but how does this Position work?
    I am aware of the fact that everytime you insert in the list , that inserted element gets a position (a number?) how do I refer/catch back that node ? Via position (number)?
    Please Help....
    I appreciate it a lot!!!

    There's no standard Java class called Position, at least none that has anything to do with lists or collections. So this must be a class or interface that somebody else wrote. At any rate, a Position parameter needs a Position object, obvious as that may sound. How do you create a Position object? Somebody with documentation of the Position class or interface might be able to help here -- is this homework?

  • Help with creating a doubly linked list

    So I have been working with this file our teacher gave us, which is his own "list" ADT which I posted below (with out the comments so it doesn't stretch the page for ever)
    My question is, I cant really creat a DLL from this because I have nothing for the head, no previous or next or any of that...So could some one help me get off to the right start? Some of my class mates were like "create a SLL and then reverse it" well thats all fine and dandy but how?
    A couple other student said "With this DLL i only had to write two lines for each method to implement the list"...Can that be done? Theres NO documentation any where on a DLL for java, and the linkedList in the java api...I dont think that's a DLL...
    I SERIOUSLY need a nudge in the right direction....
    package assignment.four.utilities;
    import java.io.Serializable;
    public interface List<E> extends Serializable
         public int size ();
         public void clear ();
         public boolean add (int index, E toAdd) throws NullPointerException,
                                                                     IndexOutOfBoundsException;
         public boolean add (E toAdd) throws NullPointerException;
         public boolean addAll (List<? extends E> toAdd) throws NullPointerException;
         public E get (int index) throws IndexOutOfBoundsException;
         public E remove (int index) throws IndexOutOfBoundsException;
         public E remove (E toRemove) throws NullPointerException;
         public E set (int index, E toChange) throws NullPointerException,
                                                                IndexOutOfBoundsException;
         public boolean isEmpty ();
         public boolean contains (E toFind) throws NullPointerException;
         public E [] toArray (E [] toHold) throws NullPointerException;
         public E [] toArray ();
         public Iterator<E> iterator ();     
    }Again with my statement. Using that List ADT HOW do you even get started in the right direction to creating a DLL? I can use this to create an array list but i dont think i can for a dll?
    Edited by: user8974754 on Nov 20, 2010 8:00 PM

    user8974754 wrote:
    Ok thats fine and dandy but we never learned how to make a DLL we learned last semester how to make a SLL and I kinda get that but again with the So, you know how to make an SLL? Then I would suggest starting with that. For instance, you know how to define a Node or Element or whatever-you-want-to-call-it class that holds Data and Next? Start with that, and see if you can work out how to add a Previous.
    "there's nothing on DLL's" except for the same line over and over "They go backwards and forwards" and Im sorry but that doesn't cut it......So, [url http://www.youtube.com/watch?v=Ijae2WHdc9I]you know how to count blocks, but you don't know how to count oranges? That is, you know how to make forward links in a list, but not backward links? Really?
    Is there any examples of Java Dlls implementing lists and bla?I'm sure there are plenty, and I'm sure your google works as well as mine.
    like we cant implement any thing else as far as I know, it can only be this list....When I said you need to implement the various pieces, I meant in the normal English sense of the word, not in the Java keyword sense. Implementing a Node in the general sense is part of "implements List" in the Java keyword sense.
    I know the asking for a sample implementation might be considered cheating in some peoples books Yup.
    but i learn best from examples, explanations and what not...There's a world of difference between an example of a different use of the concepts that you're trying to learn and just doing your work for you. Whatever concepts this lesson is teaching that are being tested and reinforced by this homework, you can find plenty of examples without somebody providing a DLL implementation for you.
    Edited by: Am I still jverd? on Nov 20, 2010 9:05 PM

  • How to update list item metadata?

    I want to implement lists.asmx > UpdateListItems method. In the update method (the caml) i would like to use barcode as a filter instead of item ID. http://msdn.microsoft.com/en-us/library/office/ms440289(v=office.14).aspx 
    How would my caml look like?
    <Batch OnError="Continue" ViewName="CA28BFCC-4CCE-4EF8-B08F-7824535E13FC">
    <Method ID="1" Cmd="Update">
          <Field Name='BarCode'>6061114511</Field>
          <Field Name="Title">New Title 2</Field>
    </Method>
    </Batch>

    Hi  ,
    You cannot use barcode as a filter instead of item ID by using OOTB  list.asmx. You could build your own custom web service that uses the either the SPQuery class or linq and gather the items based on
    a particular field value.
    For more information, please take a look at the thread:
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/af23f9f0-2640-474c-9616-522fcb639029/listserviceupdatelistitems-update-reference-field?forum=sharepointdevelopmentlegacy
    I recommend that you  update list items with listdata.svc.
    Reference:
    http://chuvash.eu/2011/12/15/update-list-items-with-listdata-svc/
    Best Regards,
    Eric
    Eric Tao
    TechNet Community Support

  • List v = new Vector() how can i write this ?

    List v = new Vector() how can i write this ?
    vector does not 'extends' List rather it 'implements' only ......so how can write this way ? ( polymorphism applies only for 'extends' ).

    my question in a simple way is :
    List some_list extends Vector
    No, List is an interface; Vector is a concrete class. Read the javadocs.
    Vector implements List
    >
    AND
    List some_list implements Vector
    are these two same in behaviour
    our  apart from theoretical differences ?thanks
    Interfaces don't have any implementation; they're pure method signatures. When a concrete class implements an interface, it makes a promise that says "I will provide implementations for exactly these methods. Any client can call a method from the interface and I will do something 'sensible' if I'm written correctly."
    From the point of view of static and dynamic types, there's no difference between interfaces and classes.
    C++ has interfaces, too - they're classes with all pure virtual methods. If you understand how C++ works, the concept shouldn't be hard.
    ArrayList is preferred precisely because it isn't synchronized by default. (You can always make it so using java.util.Collections if you wish later on.) If you don't need synchronization, why pay the performance penalty?

  • 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.

  • Help with Stacked linked lists with nodes.

    I have 5 elements, { object1, object2, object3, object4, object5}; and I add then to the stack from object1 to object5 (from left to right). So the head node > object 5 > object 4 > object3> object2 > object1. (> represents points to.) So i made a method to get the nth element of the list in the order I input it to the list. The method is called ElementsAt(int i). But some reason, it always returns the last object in the list. I included my entire code because there may be something wrong somewhere else that maybe causing it.
    Note: There is also a list interface.
    public class MyList implements List {
         * The head node.
         private Node head;
         * The node it is currently reading
         private Node curr;
         * The previous node it has read.
         private Node prev;
         * A blank Node
         private Node blank;
         * The number of elements in the list
         private int numItems;
         * Default constructor
         public MyList() {
              numItems = 0;
              head = null;
         * Add an element in front of the list.
         * @param o The object to be added.
         public void addFront(Object o){
              if(head == null) {
                   head = new Node (o, null);
              else{
                   blank = new Node(o,null);
                   curr = head;
                   while (curr != null){
                        prev = curr;
                        curr = curr.getNext();
                   blank.setNext(curr);
                   prev.setNext(blank);
              numItems +=1;
         * Add an element in the back of the list.
         * @param o The object to be added.
         public void addBack(Object o){
              curr = head;
              if (head == null){
                   head = new Node(o ,null);
              else {
                   head = new Node(o, curr);
              numItems +=1;
         * Determine whether the list contains a certain object.
         * @param o The object it searches through the list to
         * see if it is present.
         * @ returns a boolean that describes whether object is
         * in the list.
         public boolean contains(Object o){
              boolean present = false;
              curr = head;
              while ((curr != null) && (present != true)){
                   present = (o.equals(curr.getElement()));
                   curr.setNext(curr.getNext());
              return present;
         /** Remove an object in the list if it is in the list.
         * @param o The object it wants to remove.
         public void remove(Object o){
              if(head ==null){
                   return ;
              if(head.getElement().equals(o)){
                   head = head.getNext();
                   numItems -=1;
              else{
                   prev = head;
                   curr = head.getNext();
                   while ((curr!=null) && (curr.getElement() !=o)){
                        prev = curr;
                        curr = curr.getNext();
                   if (curr!=null){
                        blank = curr.getNext();
                        prev.setNext(blank);
                        numItems-=1;
         /** Determine what object is at the nth place of the list.
         * @param i the nth place of the list
         * if the number is higher than the list, it is invalid.
         * @returns The element of the nth position of the list.
         public Object elementAt(int i){
              curr = head;
              Object blank = "";
              if ( i > numItems){
                   return null;
              else{
                   i = numItems - i;
                   for (int j=1; j<=i; j++){
                        if(curr!=null){
                             blank = curr.getElement();
                             curr = curr.getNext();
                   return blank;
         /** Determine the size of the list.
         * @returns The size of the list
         public int size() {
              return numItems ;
         /** Makes the list empty
         public void makeEmpty() {
              head = new Node(null,null);
              numItems = 0;
         /** Returns The list as a string.
         * @returns String containing all elemnts of the list.
         public String toString(){
              String sum = "";
              curr = head.getNext();
              blank = head;
              prev = head;
              if(curr==null){
                   prev.setNext(null);
                   curr=prev;
              while(curr != null)
                   if(curr.getNext() ==null){
                        sum += "\n" + curr.getElement();
                        curr.setNext(null);
                   if(curr.getNext()==null)
                        prev.setNext(null);
                        prev = blank;
                        curr = prev.getNext();
                   else{
                        curr = curr.getNext();
                        prev= prev.getNext();
              if (head.getElement() !=null)
              sum +="\n" + head.getElement();
              return sum;
    }this is the program i use to test it.
    public class MyListTester {
         public static void main (String [] args)
              List list = new MyList();
              String one = "Object One";
              String two = "Object Two";
              String three = "Object Three";
              int five = 5;
              list.addFront(one);
              list.addFront(two);
              list.addFront(three);
              list.addFront(five);
              System.out.println(list);
              System.out.println();
              System.out.println(list.size());
              System.out.println(list.elementAt(2));
                    //this should print out object Two, but doesn't
              System.out.println(list.elementAt(3));
                    //this should print out object Three, but doesn't
    }

    chuang7 wrote:
    So i made a method to get the nth element of the list in the order I input it to the list.
    * The node it is currently reading
    private Node curr;
    * The previous node it has read.
    These ('curr' and 'prev') should be local variables in the methods that need them, not instance variables.
    public void addFront(Object o)
    while (curr != null){
         prev = curr;
         curr = curr.getNext();
    blank.setNext(curr);At this point 'curr' is always null so this line is redundant.
    public void addBack(Object o)You can reduce this method to two lines of code.
    public boolean contains(Object o)
    curr.setNext(curr.getNext());You are modifying the list inside the contains method?
                   for (int j=1; j<=i; j++){Rethink this loop.
    public String toString()
         prev.setNext(null);
    if(curr.getNext() ==null)
         sum += "\n" + curr.getElement()+"->"+curr.getNext();
         curr.setNext(null);
    if(curr.getNext()==null)
         prev.setNext(null);
         prev = blank;
         curr = prev.getNext();You are modifying the list in the toString() method?

  • Concrete classes implement abstract class and implements the interface

    I have one query..
    In java collection framework, concrete classes extend the abstract classes and implement the interface. What is the reason behind extending the class and implementing the interface when the abstract class actually claims to implement that interface?
    For example :
    Class Vector extends AbstractList and implements List ,....
    But the abstract class AbstractList implements List.. So the class Vector need not explicitly implement interface List.
    So, what is the reason behind this explicit definition...?
    If anybody knows please let me know..
    Thanx
    Rajendra.

    Why do you post this question again? You already asked this once in another thread and it has been extensively debated in that thread: http://forum.java.sun.com/thread.jsp?forum=31&thread=347682

  • Need help on creating a linked list with array...

    I want to create a linked listed using array method. Any suggestion on how would I start it.
    thanks

    That means I want to implement linked list using an
    array.I believe you mean you want to implement list using an array. Linked list is a very different implementation of a list, which can be combined with arrays for a niche implementation of list, but I don't think this is what you're talking about.
    Do you mind if we ask why you don't want to use ArrayList? It does exactly what you specify, plus it will increase the size of the internal array as necessary to ensure it can store the required elements.
    If you really want to make your own, have a look at the source for ArrayList (in src.jar in your JDK installation folder) - it will answer any questions you have. If you don't understand any of the code, feel free to post the relevant code here and ask for clarification.

Maybe you are looking for