Test in a LinkedList...

if there is a way to know if my LinkedList is empty and the way to display the number of element(in this case "0").
If you know how to code it could you show me the way...
thanks

Yes, there are methods for this. To display the number of elements:
yourList.size();And to check if it's empty:
yourList.isEmpty();That'll return true of false. The API can tell you all of this. Use it for future reference because it's all you need:
http://java.sun.com/j2se/1.4/docs/api/java/util/LinkedList.html

Similar Messages

  • LinkedList parameter problem

    I created a web services application a few months ago and I am now trying to add a new method that contains a LinkedList as an input parameter. I used the weblogic.webservice.clientgen command to create the needed Codec and Holder classes for a string array when I first created this application and now I am trying to do the same for a LinkedList. However when I run my code to call the web service I get the following NullPointerException:
    java.lang.NullPointerException
         at weblogic.xml.schema.binding.TypedSoapArrayCodecBase.serializeMultiDimArray(TypedSoapArrayCodecBase.java:145)
         at weblogic.xml.schema.binding.SoapArrayCodecBase.gatherContents(SoapArrayCodecBase.java:464)
         at weblogic.xml.schema.binding.CodecBase.serializeFill(CodecBase.java:279)
         at weblogic.xml.schema.binding.CodecBase.serialize_internal(CodecBase.java:216)
         at weblogic.xml.schema.binding.CodecBase.serialize(CodecBase.java:178)
         at weblogic.xml.schema.binding.RuntimeUtils.invoke_serializer(RuntimeUtils.java:188)...
    Here is code I use to register the mapping and the code I use to add the LinkedList to the call.
    TypeMappingRegistry registry = service.getTypeMappingRegistry();
    TypeMapping mapping = registry.getTypeMapping( SOAPConstants.URI_NS_SOAP_ENCODING );
    mapping.register( java.util.LinkedList.class,
    new QName("http://soapinterop.org/xsd", "LinkedList" ),
    new LinkedListCodec(),
    new LinkedListCodec() );
    QName linkedListName = new QName("http://soapinterop.org/xsd", "LinkedList");
    LinkedList test = new LinkedList();
    test.add("test");
    call.addParameter("linkedList", linkedListName, javax.xml.rpc.ParameterMode.IN);
    Can anyone help me figure out what the problem is?? I did this same thing for a String array and now I can't get it to work for a LinkedList. Thanks.

    what about below error:
    syntax error, parameterized types are only available if source level is 5.0
    Vector<String,String> a = new Vector<String,String>();
    doesn't work at all.
    i get the above syntax error with all the Collections types,
    ArrayDeque, LinkedList, Stack, HashTable, HashMap, . . .
    i think some package is something or anything else ?
    regards,
    rafi

  • How to create a program that accepts 5 digits from the user between 0 and 9

    how to create a program that accepts 5 digits from the user between 0 and 9 then put them in ascending order using link-list method..

    You can use a scanner to get user input from the command line.
    import java.util.*;
    public class Test {
        private List<Integer> list;
        private Scanner in;
        public static void main (String... args) {
            new Test ();
        public Test () {
            list = new LinkedList<Integer> ();
            in = new Scanner (System.in);
            for (int i = 0; i < 5; i ++) {
                System.out.format ("Please enter a number (%d more): ", (5 - i));
                list.add (in.nextInt ());
            Collections.sort(list, new Comparator<Integer> () {
                public int compare (Integer i1, Integer i2) {
                    return i2 - i1;
            System.out.println (list);
    }

  • Custom iterator for custom list. ClassNotFoundException()

    I'm not sure what it is I'm doing wrong in this assignment We are to create a linked list with each node containing a fixed size array [8]
    At the moment when running the speed test class (speed test tests arraylist, collection and the chunklist) my class is simply causing an infinite loop. (i think, nothing seems to be happening anyway)
    when debugging if I try to step into certain things I get a ClassNotFoundException(); for example. the constructor for the list.
    ChunkList()
        if (head == null)
            head = new Chunk<T> (head);
            tail = new Chunk<T> (head);
    }the line head = new Chunk<T>(head) causes this exception, however if I step over it in Eclipse it works fine, and seems to add data provided by the speed test. The same is happening with my iterator. When stepping over this however in the over-ridden Iterator it does not seem to be returning a ChunkItr
    import java.util.AbstractCollection;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.NoSuchElementException;
    public class ChunkList<T> extends AbstractCollection<T>
        private final int ARRAY_SIZE = 8;
        private Chunk<T> head;
        private Chunk<T> tail;
        private int numOfElements;
        @SuppressWarnings("hiding")
        private class Chunk<T>
            public Object[] data = new Object[ARRAY_SIZE];
            public Chunk<T> link;
            public int chunkSize = 0;
            @SuppressWarnings("unused")
            public Chunk()
                data = null;
                link = null;
            public Chunk(Chunk<T> link)
                this.link = link;
            public boolean equalsChunk(Chunk<T> c)
                if (c == null)
                    return false;
                else if (this.chunkSize != c.chunkSize)
                    return false;
                else if (this.link != c.link)
                    return false;
                else
                    Chunk<T> otherChunk = (Chunk<T>)c;
                    for(int i=0; i<ARRAY_SIZE; ++i)
                        if (!(this.data.equals(otherChunk.data[i])))
    return false;
    return true;
    }// end of Chunk<T>
    @SuppressWarnings("hiding")
    private class ChunkItr<T> implements Iterator<T>
    public Chunk<T> currentChunk;
    public Chunk<T> previousChunk;
    public Chunk<T> nextChunk;
    public int currentElement;
    @SuppressWarnings("unchecked")
    public ChunkItr()
    currentChunk = (Chunk<T>) head;
    previousChunk = null;
    nextChunk = (Chunk<T>) head;
    currentElement = 0;
    @Override
    public boolean hasNext()
    if (currentChunk != null)
    if (currentElement < currentChunk.chunkSize)
    return true;
    return (nextChunk != null);
    @SuppressWarnings("unchecked")
    @Override
    public T next()
    if (!hasNext())
    throw new NoSuchElementException();.
    T elementToReturn = null;
    while (elementToReturn == null)
    if (currentChunk != null)
    elementToReturn = (T) currentChunk.data[currentElement];
    if ((currentElement == ARRAY_SIZE-1) ||
    (currentElement == currentChunk.chunkSize))
    previousChunk = currentChunk;
    currentChunk = currentChunk.link;
    currentElement = -1;
    if (currentElement == 0)
    nextChunk = nextChunk.link;
    ++currentElement;
    else
    break;
    return elementToReturn;
    @SuppressWarnings("unchecked")
    @Override
    public void remove()
    if (currentChunk == null)
    throw new IllegalStateException();
    else if (currentChunk.data[currentElement] == null)
    throw new IllegalStateException();
    else
    int move = currentChunk.chunkSize - currentElement;
    for (int i=currentElement;i<move;++i)
    currentChunk.data[i] = currentChunk.data[i+1];
    // let gc do its work
    currentChunk.data[currentChunk.chunkSize] = null;
    --currentChunk.chunkSize;
    --numOfElements;
    } // did we just null first element?
    if (currentChunk.chunkSize < 0)
    if (currentChunk.equalsChunk((Chunk<T>) tail))
    tail.link = tail;
    //tail = (Chunk<T>) previousChunk;
    } // re-link
    currentChunk = currentChunk.link;
    previousChunk.link = currentChunk;
    } // end ChunkItr
    public ChunkList()
    head = null;
    tail = null;
    numOfElements = 0;
    public void addNewChunk()
    if (head == null)
    head = new Chunk<T>(head);
    tail = new Chunk<T>(head);
    else
    tail = new Chunk<T>(tail);
    @Override
    public boolean add(T t)
    try
    if (head == null)
    addNewChunk();
    tail.data[tail.chunkSize] = t;
    ++numOfElements;
    if (tail.chunkSize == ARRAY_SIZE-1)
    addNewChunk();
    else
    ++tail.chunkSize;
    return true;
    catch(Exception e)
    return false;
    @Override
    public Iterator<T> iterator()
    return new ChunkItr<T>();
    @Override
    public int size()
    return numOfElements;
    public int numOfChunks()
    int count=0;
    Chunk<T> position = head;
    while (position != null)
    count++;
    position = position.link;
    return count;
    // EOF

    I should ask this: What would be a better way to go about debugging this, besides the Eclipse debugger? because that just seems to give me runtime exceptions in places where it shouldn't.
    speedtest
    package chunklist;
    //ChunkSpeed.java
    This is a little class with a main() that runs some timing tests on
    ArrayList, LinkedList, and ChunkList.
    -- it's just static functions.
    import java.util.*;
    public class ChunkSpeed
        // number of elements
        public static final int MAX = 200000;
        public static String FOO = "Foo";
         Times a fixed series of add/next/remove calls
         on the given collection. Returns the number
         of milliseconds the operations took.
        public static long test(Collection<String> coll)
            long start = System.currentTimeMillis();
            // Build the thing up
            for (int i=0; i<MAX; i++)
                coll.add(FOO);
            // Iterate halfway through
            Iterator<String>it = coll.iterator();
            for (int i=0; i<MAX/2; i++)
                it.next();
            // Delete the next tenth
            for (int i=0; i<MAX/10; i++)
                it.next();
                it.remove();
            // Iterate over the whole thing (read-only) 5 times
            int count = 0;
            for (int i = 0; i<5; i++)
                for (String s: coll)
                    if (s != null) count++;
            long delta = System.currentTimeMillis() - start;
            return(delta);
          Runs the time test on the given collection and prints the result,
          including the class name (cute use of getClass()).
        public static void printTest(Collection<String> c)
            long time = test(c);
            System.out.printf("%s %d\n", c.getClass().toString(), time);
        //////////////////////////////MAIN METHOD//////////////////////////////
        public static void main(String[] args)
            for (int i=0; i<5; i++)
                printTest(new ArrayList<String>());
                printTest(new LinkedList<String>());
                printTest(new ChunkList<String>());
        }//end main method
    }//end class ChunkSpeedEdited by: Gcampton on Sep 2, 2010 8:57 PM

  • Counting

    I am writing a simulation class for a research project. I'm trying to find an efficient way to create test sets using LinkedLists. A number will be inputted into a method and the method is to return a set of test cases Here is an example using three integers (0, 1, 2):
    0,1
    0,2
    1,0
    1,2
    2,0
    2,1
    0,1,2
    Any ideas or recommendations on how to efficiently create these test cases?

    You should be more specific. It is not clear what you want:
    1) permutations: 6 solutions
    2) 3 digit trinary counting: 27 solutions
    3) subset enumeration: 8 solutions
    4) combinations of length k: C(3,k) solutions
    and maybe there are more I can't think of now.
    kind regards,
    Jos

  • GetFirst() question

    i am writing a program involving Linkedlists. its wierd but everytime i try to use the getFirst()method i get an error message
    MyLL.jvav:484: cannot resolve symbol
    symbol: method getFirst()
    location: interface java.util.List
    int y=list1.getFirst();
    I dont understand why this is the case if anyone could shead some light on this that would be great

    //this workable solution may serve as an example
    public class Test{
    LinkedList list = null;
    Test(){
    list = new LinkedList();
    System.out.println("constructor - init");
    private void addToList(){
    String element= "first element";
    list.addFirst(element);
    System.out.println("added");
    private String getFirstElement(){
    System.out.println("get");
    return ((String)list.getFirst()); //GET ELEMENT
    public static void main(String args[]){
    Test getElement = new Test();
    getElement.addToList();
    String value = getElement.getFirstElement();
    System.out.println("the type of the object must be declared - "+value);

  • How to print the content of LinkedList int[] and LinkedList LinkedList ?

    Hi guys, its been a long time since i posted here, and now im coming back to programming using java. My problem is, how can i print the content of the list?
    Example:
    LinkedList<int[]> list = new LinkedList<int[]>;
    int[] input = {1,2,3,4,5};
    int[] input2 = {2,32,43,54,65};
    list.add(input);
    list.add(input2);
    how can i print all the content of the linkedlist?
    Please help me..I know its a dumb question but i really dunno how.
    here is the code:
    import java.util.LinkedList;
    import java.util.Scanner;
    import java.util.Arrays;
    public class Test{
         static void printThis(String[] in){
              System.out.print("Value: ");
              for(int i = 0;i<in.length;i++){
                   System.out.print(in[i] + " ");
              System.out.println();
         static void reset(String[] val){
              for(int i = 0;i<val.length;i++){
                   val[i] = "";
         public static void main(String[] args){
              LinkedList<String[]> list = new LinkedList<String[]>();
              LinkedList<String> listTrans = new LinkedList<String>();
              System.out.print("Enter the number of records: ");
              Scanner s = new Scanner(System.in);
              int numOfRecords = s.nextInt();
              System.out.print("Enter the number of records per run: ");
              s = new Scanner(System.in);
              System.out.println();
              int numOfRecordsInMemory = s.nextInt();
              String[] getData = new String[numOfRecords];
              String[] transferData = new String[numOfRecordsInMemory];
              int numOfRuns = 0;
              int counter = 0;
              for(int i = 0;i<numOfRecords;i++){
                   counter++;
                   System.out.print("Enter value number " + counter + ": ");
                   Scanner scan = new Scanner(System.in);
                   getData[i] = scan.next();
                   listTrans.add(getData);
              if(getData.length%numOfRecordsInMemory == 0){
                   numOfRuns = getData.length/numOfRecordsInMemory;
              }else if(getData.length%numOfRecordsInMemory != 0){
                   numOfRuns =(int)(getData.length/numOfRecordsInMemory)+ 1;
              System.out.println();
              System.out.println("Number of Runs: " + numOfRuns);
         int pass = 0;
         System.out.println("Size of the main list: " + listTrans.size());
         while(listTrans.size() != 0){
              if(listTrans.size() >= numOfRecordsInMemory){
                   for(int i = 0;i<numOfRecordsInMemory;i++){
                        transferData[i] = listTrans.remove();
                   System.out.println("Size of the list: " + listTrans.size());
                   printThis(transferData);
                   System.out.println();
                   Arrays.sort(transferData);
                   list.add(transferData);
                   reset(transferData);
              }else if(listTrans.size() < numOfRecordsInMemory){
                   pass = listTrans.size();
                   for(int k = 0;k<pass;k++){
                        transferData[k] = listTrans.remove();
                   System.out.println("Size of the list: " + listTrans.size());
                   printThis(transferData);
                   System.out.println();
                   Arrays.sort(transferData);
                   list.add(transferData);
                   reset(transferData);
    //This is the part that is confusing me.
    //im trying to print it but its not working.
              System.out.println("Size of the next list: " + list.size());
    //          for(int i = 0;i<list.size();i++){
    //                    System.out.println();
    //               for(int j = 0;j<list.get(i)[j].length();j++){                    
    //                    System.out.print(list.get(i)[j] + " ");

    Here's the funnest, mabye clearest way you could do it: Use 2 Mappers
    package tjacobs.util;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import tjacobs.Arrays;
    public class Mapper <T>{
         public static interface MappedFunc<T> {
              void map(T value);
         public Mapper(T[] vals, MappedFunc<T> function) {
              this (new Arrays.ArrayIterator<T>(vals), function);
         public Mapper(Iterator<T> iterator, MappedFunc<T> function) {
              while (iterator.hasNext()) {
                   function.map(iterator.next());
         public static void main(String[] args) {
              String[] s = new String[] {"a","b", "c", "abc", "ab"};
              MappedFunc<String> func = new MappedFunc<String>() {
                   public void map(String s) {
                        if (s.toLowerCase().startsWith("a")) {
                             System.out.println(s);
              Mapper m = new Mapper(s, func);
    }

  • Iterating performance: ArrayList, LinkedList, and Hashmap for N 1,000,000

    I have seen some websites discussing about the performance of ArrayLists, LinkedLists, and Hashmaps:
    http://forum.java.sun.com/thread.jspa?threadID=442985
    http://java.sun.com/developer/JDCTechTips/2002/tt0910.html
    http://www.javaspecialists.co.za/archive/Issue111.html
    http://joust.kano.net/weblog/archives/000066.html
    If I understand it right an ArrayList in general is faster for accessing a particular element in the collection and I can't find some pro's of using a LinkedList.
    My question is: If I only use a large collection with more than 1 million elements for iterating from begin to end (i.e. for loop), is it faster to use a linked list or a custom linked list instead of an arraylist (or hashmap)? Since you can iterate "directly" through a (custom) linked list, which is not possible with a arraylist?
    Edited by: 9squared on Nov 23, 2007 1:48 PM

    Thanks for the help, I wrote some code and tested it
    import java.util.ArrayList;
    import java.util.List;
    import java.util.LinkedList;
    public class TestTemp {
         public static void main(String[] args) {
              List<Node> a = new ArrayList<Node>();
              Node b = new Node("a");
              String[] c = new String[10000000];
              Node temp = b;
              for (int i = 0; i < 10000000; i++)
                   a.add(new Node("a"));
                   temp.next = new Node("b");
                   temp = temp.next;     
                   c[i] = "c";
              long tstart;
              tstart = System.currentTimeMillis();
              for (int i = 0; i < 10000000; i++)
                   c[i] = "cc";
                   if (i%200000 == 0)
                        System.out.println("Array " + i + ": " + (System.currentTimeMillis()-tstart));
              tstart = System.currentTimeMillis();
              temp = b;
              for (int i = 0; i < 10000000; i++)
                   temp.next.text = "bb";
                   temp = temp.next;
                   if (i%200000 == 0)
                        System.out.println("LinkedList " + i + ": " + (System.currentTimeMillis()-tstart));
              tstart = System.currentTimeMillis();
              for (int i = 0; i < 10000000; i++)
                   a.get(i).text = "aa";
                   if (i%200000 == 0)
                        System.out.println("ArrayList " + i + ": " + (System.currentTimeMillis()-tstart));
    public class Node {
         public String text;
         public Node next;
         public Node(String text)
              this.text = text;
    }Here are some results in milliseconds, and indeed just iterating doesn't take very long
    Elements     Linked     Arraylist     Array
    200000     0     0     1
    400000     5     13     5
    600000     9     22     9
    800000     14     32     12
    1000000     20     42     16
    1200000     25     52     19
    1400000     31     63     23
    1600000     37     72     26
    1800000     42     82     30
    2000000     47     92     33
    2200000     51     101     37
    2400000     56     112     40
    2600000     60     123     44
    2800000     65     134     47
    3000000     69     143     51
    3200000     73     152     55
    3400000     78     162     59
    3600000     84     175     63
    3800000     103     185     67
    4000000     108     195     70
    4200000     113     207     74
    4400000     117     216     78
    4600000     122     225     81
    4800000     127     237     85
    5000000     131     247     88
    5200000     136     256     92
    5400000     142     266     97
    5600000     147     275     101
    5800000     153     286     107
    6000000     159     298     113
    6200000     162     307     117
    6400000     167     317     121
    6600000     171     326     125
    6800000     175     335     128
    7000000     180     346     132
    7200000     184     358     136
    7400000     188     368     139
    7600000     193     377     143
    7800000     197     388     147
    8000000     201     397     150
    8200000     207     410     154
    8400000     212     423     157
    8600000     217     432     162
    8800000     222     442     167
    9000000     227     452     171
    9200000     231     462     175
    9400000     236     473     178
    9600000     242     483     182
    9800000     249     495     185
    10000000     257     505     189

  • ServletException: Error testing property 'foo' in bean of type null

    Hi,
    JSF is new to me. First test pojects were fine but now i am running into some prolems. maybe you could help. here are my error message, my classes and jsps. If you need more information to solve the porblem please let me know. thanx felix
    javax.servlet.ServletException: Error testing property 'vorname' in bean of type null
         javax.faces.webapp.FacesServlet.service(FacesServlet.java:209)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
    root cause
    javax.faces.el.PropertyNotFoundException: Error testing property 'vorname' in bean of type null
         com.sun.faces.el.PropertyResolverImpl.getType(PropertyResolverImpl.java:342)
         com.sun.faces.el.impl.ArraySuffix.getType(ArraySuffix.java:240)
         com.sun.faces.el.impl.ComplexValue.getType(ComplexValue.java:208)
         com.sun.faces.el.ValueBindingImpl.getType(ValueBindingImpl.java:345)
         com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:111)
         javax.faces.component.UIInput.getConvertedValue(UIInput.java:713)
         javax.faces.component.UIInput.validate(UIInput.java:638)
         javax.faces.component.UIInput.executeValidate(UIInput.java:849)
         javax.faces.component.UIInput.processValidators(UIInput.java:412)
         javax.faces.component.UIForm.processValidators(UIForm.java:170)
         javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:912)
         javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:342)
         com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:78)
         com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)
         com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:90)
         javax.faces.webapp.FacesServlet.service(FacesServlet.java:197)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
    My Start-JSP:
    <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
    <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
    <html>
    <head>
    Eingabe Person
    </head>
    <body>
    <h3>
    Eingabe Person
    </h3>
    Bitte geben Sie ihre Daten ein:
    <f:view>
    <h:form>
    Vorname: <h:inputText id="vorname" value="#{PersonController.currentPerson.vorname}" />
    Nachname: <h:inputText id="nachname" value="#{PersonController.currentPerson.nachname}" />
    <h:commandButton action="#{PersonController.save}" value="Submit" />
    </h:form>
    </f:view>
    </body>
    </html>
    PersonController:
    package test1;
    import java.util.*;
    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.tool.hbm2ddl.SchemaExport;
    import org.hibernate.Query;
    public class PersonController {
    private SessionFactory aSessionFactory;
    private Person currentPerson=null;
    private List<Person> personList = null;
    private Session session;
    private static final String personConfirm = "personConfirm";
    private static final String test = "test";
    /** Creates a new instance of PersonController */
    public PersonController() {
    personList = new LinkedList<Person>();
    this.setUp();
    public String createPerson(){
    currentPerson = new Person();
    return personConfirm;
    public String test(){
    return test;
    public String save(){
    personList.add(currentPerson);
    Transaction transaction = null;
    transaction = session.beginTransaction();
    session.save(currentPerson);
    transaction.commit();
    return personConfirm;
    public Person getCurrentPerson(){
    return currentPerson;
    public void setCurrentPerson(Person currentPerson){
    this.currentPerson=currentPerson;
    public List<Person> getPersonList(){
    return personList;
    public void setPersonList(List<Person> personList){
    this.personList=personList;
    public void closeSession(){
    session.close();
    protected void setUp(){
    Configuration configuration = new Configuration().configure();
    // SchemaExport export = new SchemaExport(configuration);
    //export.create(false, true);
    aSessionFactory = configuration.buildSessionFactory();
    session = aSessionFactory.openSession();
    public Person loadPerson(long id){
    return (Person)session.load(Person.class, id);     
    Bean Person:
    package test1;
    * @author F.Thomas
    public class Person {
    private long id;
    private String vorname;
    private String nachname;
    /** Creates a new instance of Person */
    public Person() {
    public long getId() {
    return id;
    public void setId(long id) {
    this.id = id;
    public String getVorname() {
    return vorname;
    public void setVorname(String vorname) {
    this.vorname = vorname;
    public String getNachname() {
    return nachname;
    public void setNachname(String nachname) {
    this.nachname = nachname;
    Target JSP:
    <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
    <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
    <html>
    <head>
    Best�tigung Person
    </head>
    <body>
    <h3>
    Best�tigung Person
    </h3>
    Ergebnis Ihrer Eingabe:
    <f:view>
    <h:form>
    Vorname: <h:outputText value="#{PersonController.currentPerson.vorname}" />
    Nachname: <h:outputText value="#{PersonController.currentPerson.nachname}" />
    <h:commandButton action="success" value="Submit" />
    </h:form>
    </f:view>
    </body>
    </html>
    faces-config.xml
    <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE faces-config PUBLIC
    "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
    "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
    <!-- =========== FULL CONFIGURATION FILE ================================== -->
    <faces-config>
    <navigation-rule>
    <navigation-case>
    <from-outcome>personConfirm</from-outcome>
    <to-view-id>/person/confirm.jsp</to-view-id>
    </navigation-case>
    </navigation-rule>
    <navigation-rule>
    <navigation-case>
    <from-outcome>test</from-outcome>
    <to-view-id>/person/test.jsp</to-view-id>
    </navigation-case>
    </navigation-rule>
    <managed-bean>
    <managed-bean-name>PersonController</managed-bean-name>
    <managed-bean-class>test1.PersonController</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    <managed-bean>
    <managed-bean-name>Person</managed-bean-name>
    <managed-bean-class>test1.Person</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    </faces-config>
    web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <context-param>
    <param-name>com.sun.faces.verifyObjects</param-name>
    <param-value>false</param-value>
    </context-param>
    <context-param>
    <param-name>com.sun.faces.validateXml</param-name>
    <param-value>true</param-value>
    </context-param>
    <context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
    </context-param>
    <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet>
    <servlet-name>Start2</servlet-name>
    <servlet-class>test1.Start2</servlet-class>
    </servlet>
    <servlet>
    <servlet-name>Start3</servlet-name>
    <servlet-class>test1.Start3</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
    <servlet-name>Start2</servlet-name>
    <url-pattern>/Start2</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
    <servlet-name>Start3</servlet-name>
    <url-pattern>/Start3</url-pattern>
    </servlet-mapping>
    <session-config>
    <session-timeout>
    30
    </session-timeout>
    </session-config>
    <welcome-file-list>
         <welcome-file>
    index.jsp
    </welcome-file>
    </welcome-file-list>
    </web-app>

    A quick analysis indicates that perhaps the currentPerson attribute of the PersonController is null at render time.

  • Saving a LinkedList into a text doc using bufferwriter

    hi
    I'm having some problem attempting to save my linked into a text doc(.txt). By using the scanner class i to read another text doc and have it put each work in that document as an single element in the linkedlist. But when i try to write the linked list into a text doc it only writes the last word / element that is in the linkedlist into a text document. How do i get my bufferwriter or filewrite to same all the words and prehaps in a format that i want?
    import java.util.*;
    import java.io.*;
    public class LibraryLinkedList {
        public static void main(String[] args) throws FileNotFoundException,
       IOException{
          File file1 = new File(args[0]);
            Scanner in = new Scanner(file1);
            LinkedList<String> lst = new LinkedList<String>();
            //... Read and build list of words.
            while (in.hasNext()) {
                String word = in.next();
                lst.add(word);
           ///  loop to print list forward.
            //    Could also use an Iterator (forward only) or
            System.out.println(" Print words in order of entry");
            for (String s : lst) {
                System.out.println(s);
            /// this print statement is for testing
             BufferedWriter out = new BufferedWriter(new FileWriter(
            "s.txt"));
          PrintWriter output = new PrintWriter(out);
          output.print(s);
          output.close();
    }eg.
    1. i have a doc with words("apple chair book house")
    2. i have a testing print statement which prints the words that have been scanned and placed into linked list and it prints it like this
    apple
    chair
    book
    house
    3. then when i attempt to write into a txt doc it only has ("house") in the doc

    hey
    say i wanted to add a numbering system for each linkedlist item, i've used another for loop to try and attempt this but what happens is that it loops too much.
    eg what i wanted was something like
    1. apple 2.house 3. somthing ect
    but what happens is
    1.apple 2.apple 3.apple ... 15.apple 1.house 2.house 3 house..... 15.house
    my code is as follows
    for(String g :lst) {
                for(int i = 1; i < lst.size(); i++){
                //out.write("#" + i); for loop placing numbers and increasing
                out.write(" #"+ i + g);}
      out.write(" "); // add a new line
    out.close();
        }

  • Design choice between ArrayList and LinkedList

    Can someone clarify me which is better suited (efficient) for use?
    It appears to me that both can be used very much interchangeably at least from functionality point of view. :(

    Using the following code (and I'm sure someone will come nitpicking about it) I get the (expected, at least by me from prior experience) result that iteration over a LinkedList is about twice as fast as iteration over an ArrayList, but lookup operations on an ArrayList are substantially faster:
    package jtw.test;
    import java.util.*;
    public class SpeedTest {
        public static void main(String... args) throws Exception {
            List<Integer> linked = new LinkedList<Integer>();
            List<Integer> arr = new ArrayList<Integer>();
            for (int i = 0; i < 1e3; i++) {
                linked.add(i);
                arr.add(i);
            long r = 0;
            Date startLinked = new Date();
            for (int i = 0; i < 1e3; i++) {
                for (Integer q: linked) {
                     r += q;
            Date stopLinked = new Date();
            System.out.println("Total: " + r);
            r = 0;
            Date startArr = new Date();
            for (int i = 0; i < 1e3; i++) {
                for (Integer q: arr) {
                     r += q;
            Date stopArr = new Date();
            System.out.println("Total: " + r);
            System.out.println("LinkedList iteration: " + startLinked + " to " + stopLinked + " took " + (stopLinked.getTime() - startLinked.getTime()));
            System.out.println(" ArrayList iteration: " + startArr + " to " + stopArr + " took " + (stopArr.getTime() - startArr.getTime()));
             r = 0;
            startLinked = new Date();
            for (int i = 0; i < 1e3; i++) {
                for (int j = 999; j >= 0; j--) {
                     r += linked.get(j);
            stopLinked = new Date();
            System.out.println("Total: " + r);
            r = 0;
            startArr = new Date();
            for (int i = 0; i < 1e3; i++) {
                for (int j = 999; j >= 0; j--) {
                     r += arr.get(j);
            stopArr = new Date();
            System.out.println("Total: " + r);
            System.out.println("LinkedList lookup: " + startLinked + " to " + stopLinked + " took " + (stopLinked.getTime() - startLinked.getTime()));
            System.out.println(" ArrayList lookup: " + startArr + " to " + stopArr + " took " + (stopArr.getTime() - startArr.getTime()));
    }Gets the result:
    D:\jdk1.6.0_05\bin\java -Didea.launcher.port=7540 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA 8.0.1\bin" -Dfile.encoding=windows-1252 -classpath "D:\jdk1.6.0_05\jre\lib\charsets.jar;D:\jdk1.6.0_05\jre\lib\deploy.jar;D:\jdk1.6.0_05\jre\lib\javaws.jar;D:\jdk1.6.0_05\jre\lib\jce.jar;D:\jdk1.6.0_05\jre\lib\jsse.jar;D:\jdk1.6.0_05\jre\lib\management-agent.jar;D:\jdk1.6.0_05\jre\lib\plugin.jar;D:\jdk1.6.0_05\jre\lib\resources.jar;D:\jdk1.6.0_05\jre\lib\rt.jar;D:\jdk1.6.0_05\jre\lib\ext\dnsns.jar;D:\jdk1.6.0_05\jre\lib\ext\localedata.jar;D:\jdk1.6.0_05\jre\lib\ext\sunjce_provider.jar;D:\jdk1.6.0_05\jre\lib\ext\sunmscapi.jar;D:\jdk1.6.0_05\jre\lib\ext\sunpkcs11.jar;F:\dev\Euler\out\production\Euler;C:\Program Files\JetBrains\IntelliJ IDEA 8.0.1\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain jtw.test.SpeedTest
    Total: 499500000
    Total: 499500000
    LinkedList iteration: Wed Jan 21 07:32:41 CET 2009 to Wed Jan 21 07:32:41 CET 2009 took 30
    ArrayList iteration: Wed Jan 21 07:32:41 CET 2009 to Wed Jan 21 07:32:41 CET 2009 took 53
    Total: 499500000
    Total: 499500000
    LinkedList lookup: Wed Jan 21 07:32:41 CET 2009 to Wed Jan 21 07:32:42 CET 2009 took 424
    ArrayList lookup: Wed Jan 21 07:32:42 CET 2009 to Wed Jan 21 07:32:42 CET 2009 took 22
    Process finished with exit code 0Given the internal representation of the datatypes, this is to be expected.

  • Need Help with linkedList

    I have to write a program for my class... But I'm having trouble... if some one can help me to write the add, addall method, to print...
    where if the code... Thank You
    * SinglyLinkedList.java
    * An implementation of the List interface using a
    * singly linked list.
    * (P) 2000 Laurentiu Cristofor
    * Modified (slightly) for s03 by D. Wortman
    * Modified by Ennio Bozzetti
    // The class SinglyLinkedList provides an implementation of the List
    // interface using a singly linked list.  This differs from the Java
    // class LinkedList, which employs a doubly linked list and includes
    // additional methods beyond those required by the List interface.
    // Note: Included in this file is (at least) a "stub" method for each
    // of the required methods, as well as an implementation of the Node class.
    // This allows the file to compile without error messages and allows
    // you to implement the "actual" methods incrementally, testing as you go.
    // The List interface include some "optional" methods, some of which are
    // included here (see the List API for the meaning of this).
    // Some of the methods are preceded by comments indicating that you are
    // required to implement the method recursively.  Where there are no
    // such comments, you can provide either an iterative or a recursive
    // implementation, as you prefer.
    // There are some methods that you are asked not to implement at all.
    // Leave these as they are here: they are implemented here to just
    // throw an UnsupportedOperationException when they are called.
    // Hint: Read carefully the comments for the interface List in the
    // online documentation (Java API).  You can also take a look at the
    // implementation of the LinkedList class from the API. It uses a
    // doubly linked list and it is different in many places from what
    // you need to do here. However it may help you figure out how to do
    // some things. You shouldn't copy the code from there, rather you
    // should try to solve the problem by yourself and look into that code
    // only if you get stuck.
    import java.util.*;
    public class SinglyLinkedList implements List
      // an inner class: This is our node class, a singly linked node!
      private static class Node
        Object data;
        Node next;
        Node(Object o, Node n)
          data = o;
          next = n;
        Node(Object o)
          this(o, null);
        Node( )
          this(null,null);
      private Node head; // the "dummy" head reference
      private int size;  // the number of items on the list
      public SinglyLinkedList()
        head = new Node(); // dummy header node!
      public void add(int index, Object o)
      public boolean add(Object element)
      public boolean addAll(Collection c)
        return true;
      public boolean addAll(int index, Collection c)
        return true;
      public void clear()
      // write a recursive implementation here
      public boolean contains(Object o)
        return true;
      public boolean containsAll(Collection c)
        return true;
      public boolean equals(Object o)
        return true;
      // write a recursive implementation here
      public Object get(int index)
        return null;
      // NOT implemented: we don't cover hash codes
      // and hashing in this course
      public int hashCode()
        throw new UnsupportedOperationException();
      public int indexOf(Object o)
        return -1;
      public boolean isEmpty()
        return head.next == null;
      public Iterator iterator()
        return null;
      public int lastIndexOf(Object o)
        return -1;
      // Not implemented: The following two operations are not supported
      // since we are using a singly linked list, which does not allow
      // us to iterate through the elements back and forth easily
      // (going back is the problem)
      public ListIterator listIterator()
        throw new UnsupportedOperationException();
      public ListIterator listIterator(int index)
        throw new UnsupportedOperationException();
      // write a recursive implementation here
      public Object remove(int index)
        return null;
      public boolean remove(Object o)
        return true;
      public boolean removeAll(Collection c)
        return true;
      public boolean retainAll(Collection c)
        return true;
      // write a recursive implementation here
      public Object set(int index, Object element)
        return null;
      public int size()
        return size;
      // NOT implemented: to keep the homework reasonably simple
      public List subList(int fromIndex, int toIndex)
        throw new UnsupportedOperationException();
      public Object[] toArray()
        return null;
      public Object[] toArray(Object[] a)
        // you'll find this piece of code useful
        // it checks the exact type of the array passed as a parameter
        // in order to create a larger array of the same type.
        if (a.length < size)
          a = (Object[])java.lang.reflect.Array.
         newInstance(a.getClass().getComponentType(), size);
        // ... you need to write more code here!
        return a;
      private Node getNode(int index)
           Node p;
           if(index < 0 || index > size())
                throw new IndexOutOfBoundsException();
           if(index < size() / 2)
                p = head.next;
                for(int i = 0; i < index; i++)
                   p = p.next;
        return p;
      public static void main (String[] args){
           System.out.println("Singly Linked List");
           System.out.println();     
    }       

    Whoops, I realized that the add method returns a boolean. Unless you want to define a special contract, it should just return true or do something like this:
    public boolean add (Object o)
    {if (o == null) return false;
    // Check for dummy head node
    if (head.data == null)
    head = new Node(o, null);
    else
    // Traverse the list until we find the end
    Node next = head;
    while (next.next != null)
    next = next.next;
    next.next = new Node(o, null);
    }return true;

  • Need Help for LinkedList

    Hello.
    I need to write a code to delete from the collection of the object whose value is "Tom Smith". If the object is not in the collection, display the message "Customer not found" on the ssytem console.
    I wrote the following codes; however, I don't know if the code will delete "Tom Smith" successfuly. There's no collection of the object in my compter; therefore, I'm getting the message "Customer not found" successfuly. How could I check if the code will delete the name from the collection of the object?
    I would very appreciate your suggestion/help. Thanks in advance.
    <code>
    import java.util.*;
    public class App {
    public static void main(String[] args) {
    List customers = new LinkedList();
    int num = customers.size();
    for (int i = 0; i <= num; i++){
    if (customers.contains("Tom Smith")){
    customers.remove(i);
    else {
    System.out.println("Customer not found");
    </code>

    I changed the codes to the one you taught me.
    I added 2 customer names, make sure that they are
    added (by checking custers.size() )
    When I run the program, I get the message 'delete'.
    However, I'm not really sure if the name is
    really deleted or not.
    Is the record deleted for sure?
    Suggestion/help will be appreciated.
    thank you in advance.
    <code>
    package test;
    import java.util.*;public class App {
    public static void main(String[] args) {
    List customers = new LinkedList();
    customers.add("Mary Young");
    customers.add("Tom Smith");
    int num = customers.size();
    System.out.println("customers:"+ num);
    if (customers.contains("Tom Smith")){
    customers.remove(customers);
    System.out.println("delete");
    else {
    System.out.println("Customer not found"); } }}
    </code>

  • Problems sorting custommade linkedlist

    Hi guys, I have a problem (obviously).
    Its an assignment for school and I'm supposed to write my own LinkedList (called PhoneDirectory) instead of using the already defined one in java. After a fairly large amount of time I succeeded with that.
    To get an A though I need to also create a subclass of the PhoneDirectory called SortedPhoneDirectory with the only difference that the insert method automatically places the new Person in the right place in the list based on name. I have now succeded with that as well, but something is wrong, which brings me to my problem:
    When I access the methods in the PhoneDirectory class nothing happens - nothing at all. WHY :O:P
    Here are all my classes
    The class PhoneDirectory:
    The class PhoneDirectory is a Linked List containing Person objects.
    class PhoneDirectory
        private Node header;
        public PhoneDirectory()
            header = new Node(null );
        public void insert( Person o)
            header = new Node ( o, header);
        public void findWithName(String name)
            name = name.toLowerCase();
            Node runner = header;
            Person tmp;
            int i = 0;
            while(runner.element != null)
                tmp = get(i);
                if(tmp.getName().toLowerCase().contains(name))
                    System.out.println(tmp);
                runner = runner.next;
                i++;
        public void findWithAdress(String adress)
            adress = adress.toLowerCase();
            Node runner = header;
            Person tmp;
            int i = 0;
            while(runner.element != null)
                tmp = get(i);
                if(tmp.getAdress().toLowerCase().contains(adress))
                    System.out.println(tmp);
                runner = runner.next;
                i++;
        public void findWithPhone(String phone)
            phone = phone.toLowerCase();
            Node runner = header;
            Person tmp;
            int i = 0;
            while(runner.element != null)
                tmp = get(i);
                if(tmp.getPhoneNumber().toLowerCase().contains(phone))
                    System.out.println(tmp);
                runner = runner.next;
                i++;
        public void remove(int val)
            if(header == null)
                System.out.println("Its empty!");
            else if(val == 0)
                header = header.next;
            else
                Node runner = null;
                Node previous = null;
                runner = header.next;
                previous = header;
                int i = 1;
                while(runner.element != null)
                    if(i == val)
                        previous.next = runner.next;
                    previous = runner;
                    runner = runner.next;
                    i++;
        public void removeFirst()
            if(header == null)
                System.out.println("Its empty!");
            else
                header = header.next;
        public void print()
            Node tmp = header;
            while(tmp.element != null)
                System.out.println(tmp.element);
                tmp = tmp.next;
        public Person get(int val)
            int i = 0;
            boolean abort = false;
            Node tmp = header;
            while(val != i)
                tmp = tmp.next;
                i++;
                if(tmp.next == null)
                    abort = true;
                    break;
            if(abort)
                return null;
            else
                return tmp.element;
        public int size()
            int size = 0;
            Node tmp = header;
            while(tmp.element != null)
                tmp = tmp.next;
                size++;
            return size;
    }And here's the SortedPhoneDirectory:
    class SortedPhoneDirectory extends PhoneDirectory
        private Node header;
        public SortedPhoneDirectory()
            header = new Node(null);
        public void insert(Person o)
            Node newNode = new Node();
            newNode.element = o;
            if(header.element == null)
                header = newNode;
            else if(header.element.getName().compareToIgnoreCase(o.getName()) >= 0)
                newNode.next = header;
                header = newNode;
            else
                Node runner = header.next;
                Node previous = header;
                while(runner != null && runner.element.getName().compareToIgnoreCase(o.getName()) < 0)
                    previous = runner;
                    runner = runner.next;
                newNode.next = runner;
                previous.next = newNode;
    }The class Node that the linkedlist contains:
    class Node
        public Person element;
        public Node next;
          // Constructors
        public Node()
            next = null;
            element = null;
        public Node( Person theElement )
            this( theElement, null );
        public Node( Person theElement, Node n )
            element = theElement;
            next    = n;
    }The class Person that the Nodes are containing:
    class Person implements Comparable
        private String name;
        private String address;
        private String phone;
        public Person( String n, String ad, String p )
            name = n; address = ad; phone = p;
        public String toString( )
            return getName( ) + "\t"+ getAdress()+ "\t" + getPhoneNumber( );
        public final String getName( )
            return name;
        public final String getAdress( )
            return address;
        public final String getPhoneNumber( )
            return phone;
        public int compareTo( Object other)
            Person p=(Person)other;
            if(name.compareTo(p.getName())<0)
                return -1;
            else if(name.compareTo(p.getName())>0)
                return 1;
            else
                return 0;
    }And last my main program:
    public class telefonKatalog
        static String name;
        static String address;
        static String phone;
        public static void main(String[] args)
            SortedPhoneDirectory catalog =new SortedPhoneDirectory();
            catalog.insert(new Person("Donald","Paris", "10245630"));    //I just use these for testing
            catalog.insert(new Person("Jacob","London", "63294063"));
            catalog.insert(new Person("Max","Rome", "63215371"));
            for(;;)
                System.out.println("\n\nMain Menu\n____________________\n");
                System.out.println("1. Add a new person to the Phone Directory.");
                System.out.println("2. Find a person in the Phone Directory.");
                System.out.println("3. Remove a person from the Phone Directory");
                System.out.println("4. Print the whole Phone Directory");
                System.out.println("5. Exit.\n");
                char choice = Keyboard.readChar();
                switch(choice)
                    case '1':
                        System.out.println("\nAdd a new person to the Phone Directory\n______________________________________\n");
                        System.out.println("Name: ");
                        name = Keyboard.readString();
                        System.out.println("\nAdress: ");
                        address = Keyboard.readString();
                        System.out.println("\nPhone Number: ");
                        phone = Keyboard.readString();
                        catalog.insert(new Person(name, address, phone));
                        System.out.println("\nThe person has been added.\n");
                        break;
                    case '2':
                        System.out.println("\nFind a person in the Phone Directory.\n_________________________________\n");
                        System.out.println("1. Find by name.");
                        System.out.println("2. Find by address.");
                        System.out.println("3. Find by phone number\n");
                        choice = Keyboard.readChar();
                        switch(choice)
                            case '1':
                                System.out.println("\nFind by name.\n___________________\n");
                                System.out.println("Write the name of the person you are looking for:\n");
                                name = Keyboard.readString();
                                System.out.println();
                                catalog.findWithName(name);
                                break;
                            case '2':
                                System.out.println("\nFind by address.\n___________________\n");
                                System.out.println("Write the address:\n");
                                address = Keyboard.readString();
                                System.out.println();
                                catalog.findWithAdress(address);
                                break;
                            case '3':
                                System.out.println("\nFind by Phone Number.\n___________________\n");
                                System.out.println("Write the phone number:\n");
                                address = Keyboard.readString();
                                System.out.println();
                                catalog.findWithPhone(address);
                                break;
                            default:
                                System.out.println("\nUnvalid character!\n");
                                break;
                        break;
                    case '3':
                        System.out.println("\nRemove a person from the Phone Directory.\n____________________________________\n");
                        System.out.println("Write the name of the person you want to remove.\n");
                        String strChoice = Keyboard.readString();
                        boolean result = false;
                        for(int i = 0; i < catalog.size(); i++)
                            name = catalog.get(i).getName();
                            if(name.contains(strChoice))
                                catalog.remove(i);
                                System.out.println(name + " has been removed");
                                result = true;
                        if(!result)
                            System.out.println("There are no such person");
                        break;
                    case '4':
                        System.out.println("\nThe whole Phone Directory: \n_____________________________\n");
                        catalog.print();
                        System.out.println("\n_____________________________\n");
                        break;
                    case '5':
                        System.exit(0);
                    default:
                        System.out.println("\nUnvalid character!\n");
    }Its pretty long, sorry about that.. =)
    In the main program it all workes perfectly apart from the sorting if you change
    SortedPhoneDirectory catalog = new SortedPhoneDirectory(); into PhoneDirectory catalog = new PhoneDirectory();
    What is wrong about this code?? :O:(
    Edited by: YZF-R1 on 2008-maj-23 16:55

    YZF-R1 wrote:
    now thats just mean =( Why is that mean? I mean, you didn't learn something soon enough, and I am mean for not spoon feeding you the answer so that you can cheat by handing in work that is not your own? You already did that you just told us! This is called plagiarism and could get you expelled from school.
    I will sit down and learn all of that later when I have time, Sure. You should have learnt it sooner.
    but my deadline is tomorrow and its the last project of the course, so the teacher thought he would make up something extra. When I asked him if he could help me with my problem he couldn't even fix it, he thought everything looked as it was supposed to and so on.. :'( Come on, pleease :'(Christ, stop that!

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

Maybe you are looking for

  • DATA_LENGTH in all_tab_columns in BYTE/CHAR???

    Hi in the Oracle 11gR2 or 10gR2 documentation you find the following description of ALL_TAB_COLUMNS.DATA_LENGTH. DATA_LENGTH      NUMBER      NOT NULL      Length of the column (*in bytes*)But what about VARCHAR2 fields which have been created with N

  • Organizing videos by year then event in folders?

    I organize my photos in Aperture in folders by year then event..2011, 2012, etc. How can I do this in Final Cut....do I create a new library for each year? After a few years of video at almost every event I just have a string of events on the left co

  • Can i import a video track into Logic Express?

    I need to look over what is lacking in LE.

  • How to use matlab program in formula node in labview?

    hi, i've got one equation of voltage regulation. so i did create program for that in matlab.and want to use it in formula node in labview.but i don't know how to do that.can someone please help me for that? regards bhavin

  • Cant sort photos manually

    Recently imported some photos and in the event file for the photos I am UNABLE to sort manually. I can sort by any other criteria however. How can I sort manually? Do I need to create a new album to sort manually? It appears so. But this is a PAIN wh