Help abstract classes linked list

I have a base abstract class Vegetable which is basically Node for a linkedlist
The base class Vegetable has a few abstract methods Pumpkin, Carrot, Potato basically extends Vegetable
Another class called VegetableCollection
basically in VegetableCollection
can this be done if the objects are different types eg Pumpkin, potato, Carrot?
public void add(Vegetable addObject)
head = new Vegetable(addObject);
}

I have a base abstract class Vegetable which is basically Node for a linkedlist
The base class Vegetable has a few abstract methods Pumpkin, Carrot, PotatoYou probably wouldn't have abstract methods with those names. Abstract methods are methods that you will need to define in every subclass. And a subclass called Pumpkin probably won't have meaningful definitions for methods called Carrot and Potato.
can this be done if the objects are different types eg Pumpkin, potato, Carrot?
public void add(Vegetable addObject)
head = new Vegetable(addObject);
}Here is an example of "polymorphism" at work:
import java.util.*;
abstract class Vegetable
  public abstract void identify();
class Carrot extends Vegetable
  public void identify()
    System.out.println("I'm a Carrot.");
class Pumpkin extends Vegetable
  public void identify()
    System.out.println("I'm a Pumpkin.");
public class Test
  public static void main(String args[])
    LinkedList<Vegetable> myVegetables = new LinkedList<Vegetable>();
    myVegetables.add(new Carrot());
    myVegetables.add(new Pumpkin());
    Iterator<Vegetable> i = myVegetables.iterator();
    Vegetable v = null;
    while(i.hasNext())
      v = i.next();
      v.identify();
output:
I'm a Carrot.
I'm a Pumpkin.To get polymorphism to work, you need to:
1) Define a base class with a method that you want in all the subclasses.
2) Override the method in the subclasses so that it does what's necessary for that subclass.
3) Store the subclass objects in a variable(or collection) whose type is the base class.
4) Call the method on the base type variable. Then through the magic of polymorphism, java will examine the actual object stored in the base type variable to determine what subclass it is, and then java will call the version of the method in that subclass.
As the previous poster mentioned, you need to define a class called Node, which has head, previous, and next members. Your Node class will also have a member variable called veggie, which will be of type Vegetable. Then you can assign a Carrot, Pumpkin, or Potato object to that member variable.
I assume this is an exercise where you have to create your own linked list. Otherwise, you can use the linked lists provided by java, which are very easy to use.

Similar Messages

  • Help needed in linked lists...

    I have been working on this computer assignment lately but I still don't understand linked lists yet..I did an assignment on array based implementation and now I am supposed to do the same thing in linked list implementation..
    I need help on how to change this into a linked list implementation..any help would be appreciated. Thank you..below is the code for the array based implementation..the only thing that needs change here is after where is says Array-based implementation of the ADT list.
    public class ListArrayBasedDriver {
      public static void main(String [] args) {
        ListArrayBased myGroceryList = new ListArrayBased();
        myGroceryList.add(1,"milk");
        myGroceryList.add(2,"eggs");
        myGroceryList.add(3,"butter");
        myGroceryList.add(4,"pecans");
        myGroceryList.add(5,"apples");
        myGroceryList.add(6,"bread");
        myGroceryList.add(7,"chicken");
        myGroceryList.add(8,"rice");
        myGroceryList.add(9,"red beans");
        myGroceryList.add(10,"sausage");
        myGroceryList.add(11,"flour");
        printList(myGroceryList); //print out original List
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("adding juice for 5th item...");
        myGroceryList.add (5, (Object) "juice");  //add juice
        System.out.println("item 5 is: " + myGroceryList.get(5)); //get position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("removing juice...");
        myGroceryList.remove (5); //remove item at position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
      public static void printList(ListArrayBased myList)
            //method prints a list, numbering the values,  e.g, "1.  milk" .... "5.  juice".... etc.
            int i;
            for(i=1; i <= myList.size(); i++)
                String tempString = new String((String)myList.get(i));
                System.out.println(i+" "+ tempString);
    // Array-based implementation of the ADT list.
    class ListArrayBased {
        private static final int MAX_LIST = 50;
        private Object items[];  // an array of list items
        private int numItems;  // number of items in list
        public ListArrayBased()
        // creates an empty list
             items = new Object[MAX_LIST];
             numItems = 0;
        }  // end default constructor
        public boolean isEmpty()
          return (numItems == 0);
        } // end isEmpty
        public int size()
           return numItems;
        }  // end size
        public void removeAll()
          // Creates a new array; marks old array for
          // garbage collection.
          items = new Object[MAX_LIST];
          numItems = 0;
        } // end removeAll
        public void add(int index, Object item) throws  ListIndexOutOfBoundsException
          if (numItems > MAX_LIST)
            throw new ListException("ListException on add");
        }  // end if
          if (index >= 1 && index <= numItems+1)
            // make room for new element by shifting all items at
            // positions >= index toward the end of the
            // list (no shift if index == numItems+1)
            for (int pos = numItems; pos >= index; pos--) {
              items[translate(pos+1)] = items[translate(pos)];
          } // end for
          // insert new item
          items[translate(index)] = item;
          numItems++;
          else
          {  // index out of range
            throw new ListIndexOutOfBoundsException(
             "ListIndexOutOfBoundsException on add");
          }  // end if
        } //end add
        public Object get(int index) throws ListIndexOutOfBoundsException
          if (index >= 1 && index <= numItems)
            return items[translate(index)];
          else 
          {  // index out of range
            throw new ListIndexOutOfBoundsException(
              "ListIndexOutOfBoundsException on get");
          }  // end if
        } // end get
        public void remove(int index) throws ListIndexOutOfBoundsException
          if (index >= 1 && index <= numItems)
            // delete item by shifting all items at
            // positions > index toward the beginning of the list
            // (no shift if index == size)
                for (int pos = index+1; pos <= size(); pos++) {
                    items[translate(pos-1)] = items[translate(pos)];
          }  // end for
          numItems--;    
          else
          {  // index out of range
            throw new ListIndexOutOfBoundsException("ListIndexOutOfBoundsException on remove");
          }  // end if
        } // end remove
        private int translate(int position) {
        return position - 1;
       } // end translate
    }  // end ListArrayBased
    class ListException extends RuntimeException
      public ListException(String s)
        super(s);
      }  // end constructor
    }  // end ListException
    class ListIndexOutOfBoundsException
                extends IndexOutOfBoundsException {
      public ListIndexOutOfBoundsException(String s) {
        super(s);
      }  // end constructor
    }  // end ListIndexOutOfBoundsException

    Could someone check for me if this will work and if it doesn't what I need to do to make it work..Thanks...
    public class ListArrayBasedDriver {
      public static void main(String [] args) {
        ListArrayBased myGroceryList = new ListArrayBased();
        myGroceryList.add(1,"milk");
        myGroceryList.add(2,"eggs");
        myGroceryList.add(3,"butter");
        myGroceryList.add(4,"pecans");
        myGroceryList.add(5,"apples");
        myGroceryList.add(6,"bread");
        myGroceryList.add(7,"chicken");
        myGroceryList.add(8,"rice");
        myGroceryList.add(9,"red beans");
        myGroceryList.add(10,"sausage");
        myGroceryList.add(11,"flour");
        printList(myGroceryList); //print out original List
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("adding juice for 5th item...");
        myGroceryList.add (5, (Object) "juice");  //add juice
        System.out.println("item 5 is: " + myGroceryList.get(5)); //get position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("removing juice...");
        myGroceryList.remove (5); //remove item at position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
      public static void printList(ListArrayBased myList)
            //method prints a list, numbering the values,  e.g, "1.  milk" .... "5.  juice".... etc.
            int i;
            for(i=1; i <= myList.size(); i++)
                String tempString = new String((String)myList.get(i));
                System.out.println(i+" "+ tempString);
    // Linked List-based implementation of the ADT list.
    class ListNode
         //class to represent one node in a list
         class ListNode
              //package access members; List can access these directly
              Object data;
              ListNode nextNode;
              //contructor creates a ListNode that refers to object
              ListNode( Object object)
                   this( object, null );
              } //end ListNode one-argument constructor
              //constructor creates ListNode that refers to
              // Object and to the next ListNode
              ListNode ( Object object, ListNode node)
                   data = object;
                   nextNode = node;
              // end ListNode two-argument contructor
              //return reference to data in node
              Object getObject()
                   return data; // return Object in this mode
              //return reference to next node in list
              ListNode getNext()
                   return nextNode; // get next node
              } // end method getNext
    } //end class ListNode
    //class List Definition
    public class List
         private ListNode firstNode;
         private ListNode lastNode;
         private String name; // string like " list " used in printing
         //contructor creates empty List with " list " as the name
         public List()
              this(" list ");
         } //end List no-arguement constructor
    //contructor creates an empty list with a name
    public List( String listName )
         name = listname;
         firstNode = lastNode = null;
    } //end List no-arguement contructor
    //insert Object at front of List
    public void insertAtFront ( object insertItem )
         if ( isEmpty() ) //firstNode and lastNode refer to same object
              firstNode = lastNode = newListNode( insertItem );
         else // firstNode refers to new node
              firstNode = new ListNode ( insertItem, firstNode );
    } // end method insertAtFront
    // insert Object at end of List
    public void insert AtBack ( Object insertItem )
         if ( isEmpty() ) //firstNode and lastNode refer to same object
              firstNode = new ListNode ( insertItem );
         else // firstNode refers to new node
         firstNode = new ListNode (insertItem, firstNode );
    } // end method insertAtFront
    // insert Object at end of List
    public void insertAtBack ( Object insertItem )
         if ( isEmpty() ) //firstNode and LastNode refer to same Object
              firstNode = lastNode = new ListNode ( insertItem );
         else // lastNode = lastNode.nextNode = new ListNode ( insertItem );
    } // end method insertAtBack
    //remove first node from List
    public Object removeFromFront() throws EmptyListException
         if( isEmpty() ) //throw exception if list is empty
         throw new EmptyListException( name );
         object removedItem = firstNode.data; //retrieve data being removed
    // update references firstNode and lastNode
    if (firstNode == lastNode )
         firstNode =lastNode = null;
    else
         firstNode = firstNode.nextNode;
         return removedItem; // return removed node data
    } //end method removeFromFront
    //remove last node from List
    Public Object removeFromBack() throws EmptyListException
         If ( isEmpty() ) // throw exception if list is empty
              throw new EmptyListException( name );
         Object removedItem = lastNode.data; // retrieve data being removed
         // update references firstNode and lastNode
         If ( firstNode == lastNode )
              firstNode = lastNode = null;
         else // locate new last node
              ListNode current = firstNode;
              // loop while current node does not refer to lastNode
              while ( current.nextNode != lastNode )
                   current = current.nextNode;
              lastNode = current; // current is new lastNode
              current.nextNode = null;
         } // end else
         return removedItem; // return removed node data
    } // end method removeFromBack
    // determine whether list is empty
    public boolean isEmpty()
         return firstNode == null; // return true if list is empty
    }     // end method isEmpty
    //output List contents
    public void print()
         if (isEmpty() )
              System.out.printf(�Empty %s\n�, name );
              return;
         System.out.printf(�The %s is: �, name );
         ListNode current = firstNode;
         //while (current != null )
              System.out,printf(�%s �, current.data );
              current = current.nextNode;
         } //end while
         System.out.println( �\n� );
    } //end method print
    } end class List

  • I need help with circular linked list

    Hi,
    I need help with my code. when I run it I only get the 3 showing and this is what Im supposed to ouput
    -> 9 -> 3 -> 7
    empty false
    9
    empty false
    3
    -> 7
    empty false
    Can someone take a look at it and tell me what I'm doing wrong. I could nto figure it out.
    Thanks.This is my code
    / A circular linked list class with a dummy tail
    public class CLL{
         CLLNode tail;
         public CLL( ){
              tail = new CLLNode(0,null); // node to be dummy tail
              tail.next = tail;
         public String toString( ){
         // fill this in. It should print in a format like
         // -> 3 -> 5 -> 7
    if(tail==null)return "( )";
    CLLNode temp = tail.next;
    String retval = "-> ";
         for(int i = 0; i < -999; i++)
    do{
    retval = (retval + temp.toString() + " ");
    temp = temp.next;
    }while(temp!=tail.next);
    retval+= "";}
    return retval;
         public boolean isEmpty( ){
         // fill in here
         if(tail.next == null)
              return true;
         else{
         return false;
         // insert Token tok at end of list. Old dummy becomes last real node
         // and new dummy created
         public void addAtTail(int num){
         // fill in here
         if (tail == null)
                   tail.data = num;
              else
                   CLLNode n = new CLLNode(num, null);
                   n.next = tail.next;
                   tail.next = n;
                   tail = n;
         public void addAtHead(int num){
         // fill in here
         if(tail == null)
              CLLNode l = new CLLNode(num, null);
              l.next = tail;
              tail =l;
         if(tail!=null)
              CLLNode l = new CLLNode(num, null);
              tail.next = l;
              l.next = tail;
              tail = l;
         public int removeHead( ){
         // fill in here
         int num;
         if(tail.next!= null)
              tail = tail.next.next;
              //removeHead(tail.next);
              tail.next.next = tail.next;
         return tail.next.data;
         public static void main(String args[ ]){
              CLL cll = new CLL ( );
              cll.addAtTail(9);
              cll.addAtTail(3);
              cll.addAtTail(7);
              System.out.println(cll);          
              System.out.println("empty " + cll.isEmpty( ));
              System.out.println(cll.removeHead( ));          
              System.out.println("empty " + cll.isEmpty( ));
              System.out.println(cll.removeHead( ));          
              System.out.println(cll);          
              System.out.println("empty " + cll.isEmpty( ));
    class CLLNode{
         int data;
         CLLNode next;
         public CLLNode(int dta, CLLNode nxt){
              data = dta;
              next = nxt;
    }

    I'm not going thru all the code to just "fix it for you". But I do see one glaringly obvious mistake:
    for(int i = 0; i < -999; i++)That says:
    1) Initialize i to 0
    2) while i is less than -999, do something
    Since it is initially 0, it will never enter that loop body.

  • Help PLEASE with linked list. Inserting a string in the middle of

    I'm trying to insert new strings to a linked list but it seem i cant never insert. the following code has the instructions. What i'm I not doing right? If i try to use the code, the new strings don't go through
    please help someone
    // This method should insert a new node containing the string newString immediately after the first
        // occurrence of the string aString in the list. If aString is not in the list, the method should add a node
        // containing newString to the tail of the list.
        public void insertAfter(String newString, String aString)
            StringLLNode newNode = new StringLLNode();
            newNode.setData(newString);
            //Check if HeadNode == aString
            if (headNode.getData().equalsIgnoreCase(aString))
                headNode = newNode;
            //rest of the nodes
            StringLLNode currNode = headNode;
            while(currNode != null)
                if (currNode.getData().equalsIgnoreCase(aString))
                        newNode.setNext(currNode);
                        //System.out.println("It went THROUGH");
                currNode = currNode.getNext();
            //Last Node
            if (currNode != null)
                newNode.setNext(headNode);
        }

    I have to agree with flounder, go grab a pen and paper and logically work thru the code snippet you posted.
    public void insertAfter(String newString, String aString)
            StringLLNode newNode = new StringLLNode();
            newNode.setData(newString);
            //Check if HeadNode == aString
            if (headNode.getData().equalsIgnoreCase(aString))
                headNode = newNode;
            //rest of the nodes
            StringLLNode currNode = headNode;
            while(currNode != null)
                if (currNode.getData().equalsIgnoreCase(aString))
                        newNode.setNext(currNode);
                        //System.out.println("It went THROUGH");
                currNode = currNode.getNext();
            //Last Node
            if (currNode != null)
                newNode.setNext(headNode);
    }Given a linked list [A-E] we have: A => B => C => D => E. Each Node is referencing the node to it's right, so A references B, D references E etc.
    For example take aString = "A" and newString = "AB". Your code suggests the following:
    1. Create new_node "AB"
    2. if head[A] equals aString[A], TRUE
    2.a head = new_ node
    Now the resulting linkedlist is the following:
    AB => Null
    what happened to the rest of the list?
    Now we go on to your updated example, we result in the following list:
    A => AB => Null
    hmm do you see a pattern here? when inserting a new node we are disregarding any reference to the tail of the list.
    Extending on that idea we have the following pseudo code
    1. if node to be inserted
    1.a new_node.next = list_tail
    1.b current_node.next = new_node
    A => B => C => D => E, where newnode=AA
    AA => B => C => D => E //using 1.a
    A => AA => B => C => D => E //using 1.b
    Mel

  • Help with Library link lists ..

    Hi ,
    I am working with Scott Mazur on a incorporating 8.1.7 in our code bace for our next product release. I am having problems with defining the library link list needed for builds. In the documentation it makes referance to $ORACLE_HOME/precomp/demo/proc which I cannot find. I have installed the 8.1.7 on 3 platforms (Solaris, AIX and NT ) and none of the system have this information. Can you please point me to where I may find some help in this area. We are in a critical path right now so I would appreciate any help you could give me. The sooner the better.
    Thank you for your time and help ,
    Cheryl Pollock
    Lockheed Martin Global Telecommunications .
    Formtek
    Pittsburgh office .
    (412) 937-4970
    null

    You actually shouldn't try to get the library link lists directly. Rather, you should use the $ORACLE_HOME/rdbms/demo/demo_rdbms.mk makefile like this:
    make -f $ORACLE_HOME/rdbms/demo/demo_rdbms.mk build EXE=yourexecutable OBJS="object list"
    where yourexecutable is the name for your executable and the OBJS= includes a quoted list of all your object and library files.
    null

  • Including Help in the Linked List Entries

    Hi,
    Can any one explain how to include Help text to the Linked List Entries like including normal help in the other APEX 2.2 items?
    Thanks
    Chitra

    Hi santhosh
    while you are creating the fieldcatalog there is a field called 'ROLLNAME' - Data element for F1 help.
    If your F1 help is in reference to this data element you can specifiy it here so that it appears on the List viewer. Otherwise you have to create your own data element with the documentation and specify it here for it to appear.
    In the Grid control, you can use events for triggering the same.
    Hope this helps.
    Reward points.
    Regards
    Meera

  • Hi i need help with my linked list

    hello
    im having trouble with my list
    this is where i create the studentlinked list. within my constructor for my college.
    public class MyCollege {
         private int capacity;
         public MyCollege(){
              StudentLinkedList studentList = new StudentLinkedList();
         }now my problem is in my add student method
    here it is.
    at the end of the method where i add the student to the linked list (studentList.add(aStudent);)is my problem. it says that studentList cannot be resolved.
    i understand that it cant find studentList. but i am creating it.
    why isnt it working???????????????????
    public static void main(String[] args) {
              MyCollege mc1 = new MyCollege();
         public void addStudent(int i){
              try{
                   Student aStudent = new Student();
                   String name,studentNumber, programmeCode;
                   int yearBegan;
                   if(i < capacity){
                        // this defines the buffer that will hold the data to be input
                        BufferedReader theDataStream;
                        theDataStream = new BufferedReader(new InputStreamReader(System.in));
                        //enter the details of the student
                        System.out.println("Enter in the name of the student followed by their student number");
                        System.out.println("followed by the year they began in the college a and then the course code");
                        System.out.println(" hit enter after each one");
                        name = theDataStream.readLine();
                        studentNumber = theDataStream.readLine();
                        yearBegan = Integer.parseInt(theDataStream.readLine());
                        programmeCode = theDataStream.readLine();
                        aStudent.setName(name);
                        aStudent.setStudentNumber(studentNumber);
                        aStudent.setYearBegan(yearBegan);
                        aStudent.setProgrammeCode(programmeCode);
                        studentList.add(aStudent);
                   }//end if
              }//end try
              catch(IOException e) {
                   System.out.println(e.getMessage());
         }

    cheers got it striaght away
         private int capacity;
         private StudentLinkedList studentList;
         

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

  • Need help in solving Linked lists queries

    I have encountered this code
    part a
    Node head, tail;
    head = null;
    tail = null;
    head = new Node("Beef", head); //what does that mean?part b
    Node head, tail;
    head = null;
    tail = null;
    node  new 3 = new Node("Pork");
    tail.next = new3;
    tail = new3;I am told to use diagrams to show the results of these codes. How to go about solving it?

    part aWhat do you think? You can see that it creates a node, and it assigns the new node to head.
    part bSame applies here. What do you think it does? You can see that it creates a new node, and uses the tail variable.
    Try draw it all on a paper.

  • Help on Linked List

    Hey people, i need a small help on my linked list.
    Ok, what i'm trying to do is have a search function with a linked list using strings. First i will have a string, i will then compute the ASCII value for that and take MOD 71 lets say. For example, a string has an ASCII value of 216, MOD 71 of this gives me 3. I will then have an array of 71, and each array will point to a linked list. There will be as many linked list as there are of arrays (71). I will then store this string at index [3] in the linked list in which the array points to.
    My problem for now is, how do i for example create 71 linked list? So far i can create only 1. To create another is easy, but if i have 71 the code will be too much. Is there an iterator i could use that easily creates 71? Sorry about this, i'm not really good with linked list with Java. Anyway, here is what i have now :).
    public class MyLinkedListElement {   
            String string;
            MyLinkedListElement next;
            public MyLinkedListElement(String s) {   
                string = s;
                next = null;   
            public MyLinkedListElement getNext() {
                return next;       
            public String getValue() {
                return string;
    public class MyLinkedList {
        public static MyLinkedListElement head;
        public MyLinkedList() {   
            head = null;
       public static void addToHead(String s) {
            MyLinkedListElement a = new MyLinkedListElement(s);
            if (head == null) {
                head = a;
            } else {
                a.next = head;
                head = a;       
        public static void main(String[] args) {
              String[] arr = {"Bubble", "Angie", "Bob", "Bubble", "Adam"};
              for (int i = 0; i < arr.length; i++) {
                          addToHead(arr);
    MyLinkedListElement current = head;
    while (current != null) {
    System.out.println(current.getValue());
    current = current.next;
    }I can have an array of strings and easily add them to a linked list.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    I am very confused now, i just need to store a string value inside an array of linked list. But i can't somehow do it. I am very close, i can store the value in a linked list but the array of linked list, this is what i have.
    public class MyLinkedListElement {   
            String string;
            MyLinkedListElement next;
            public MyLinkedListElement(String s) {   
                string = s;
                next = null;   
            public MyLinkedListElement getNext() {
                return next;       
            public String getValue() {
                return string;
    public class MyLinkedList {
        public MyLinkedListElement head;
        public MyLinkedList() {   
              head = null;
        public void addToHead(String s) {
             MyLinkedListElement  a = new MyLinkedListElement(s);
             MyLinkedList[] arrayOfLinkedLists = new MyLinkedList[71];
             for(int i = 0; i < arrayOfLinkedLists.length; i++) {
                 arrayOfLinkedLists[i] = new MyLinkedList();
             if (head == null) {    
                 head = a;
             } else {
                 a.next = head;
                 head = a;       
        public void print(MyLinkedListElement current) {
              while (current  != null) {
                    System.out.println(current.getValue());
                    current = current.next;
        public static void main(String[] args) {
              String[] arr = {"Bubble", "Angie", "Bob", "Bubble", "Adam"};
              MyLinkedList listInstance = new MyLinkedList();
              for (int i = 0; i < arr.length; i++) {
                    listInstance.addToHead(arr);
    MyLinkedListElement current = listInstance.head;
    listInstance.print(current);

  • Please help me :'( , I really need help in Linked List & Recursion program.

    Hi everybody..
    I hope all of you are ok..
    I'm new member in this forum and I hope anyone can help me in Linked List $ Recursion issue..
    I should write a Java program that implements a linked list of objects. This program / class will have the following methods:
    1- //print each node starting from startNode upto the end node in the list
    void writeList(Node startNode)
    2- //insert a new element to the end of the list
    void insertEnd(Object element)
    3- //Print each element statring from first element in list to the last element then start //printing each element from the last element to the first element
    void writeMirror()
    4- //delete the last node.
    void deleteEnd()
    5- //returns the number of the nodes in the list.
    int lengthList(ListNode x)
    Implement the above methods using the following restrictions:
    1- All above methods must be implemented as a recursive method.
    2- For the given linked list class, there is only a head reference
    variable, pointing the beginning of the list. Thus there is no last or
    end reference variable.
    I don't know how to write this program :'( ..
    I need your help guys and I will be so happy if anyone can do it for me ..
    The sad girl
    MaRia :(

    Any body can give me any idea any hint that may help
    me ??Hint that will help you: get a personal tutor. This is the wrong place to learn how to program. And you definitely won't learn by having your homework done for you.
    Oh, and I don't care at all that your hamster has diarrhea, your boyfriend broke up with you, both of your parents are dead and unemployed, that you have to look after your 231 siblings all by yourself and that you're forced to take this class and rather want to do something completely different.
    Heard it all before.

  • Instance of one of implementations of abstract class depending on context??

    Hi all,
    I just wonder if it is possible in Java to call creation of a new instance of an implementation of an abstract class depending on context.
    I mean something like:
    abstract class Abstract
    //1st implementation of Abstract class
    class Concrete1 extends Abstract
    //2nd implementation of Abstract class
    class Concrete2 extends Abstract
    }And now, somewhere else in the code, I would really need to call something like this:
    Abstract test1 = new ...(); //here I need sometimes to be created instance of Concrete1, sometimes instance of Concrete2
    Is there a way how to do this??

    Some more concrete code if it helps:
    Abstract class:
    * Individual.java
    * Created on 21. leden 2007, 1:08
    package genetics;
    * Abstract class defining fields and methods of one individual for genetic algorithms
    * This class is supposed to be implemented according to problem to be solved
    * @author Richard V�tek
    * @version 1.0
    abstract public class Individual implements Comparable<Individual>
       * Create random chromosomes for this individual
      protected abstract void createRandomChromosomes();
       * Count fitness of this individual
       * This number says how good is this individual (the higher number the better).
       * Better fitness means that this individual is closer to solution.
       * @return  int   Fitness of this individual
      protected abstract int getFitness();
       * Cross-breed this individual with another individual
       * This leaves untouched number of chromosomes to certain (randomly generated) position.
       * From this position on, it will swap chromosomes between this and another individual.
       * So this individual gets changed (cross-breeded) as well as the other, which is returned
       * as result of this method.
       * @param   other              The other individual to cross-breed with
       * @return  Individual         Hybrid of this and another individual (in fact, the other individual
       *                             after cross-breed (this (source) individual gets changed too after cross-breed)
      protected abstract Individual crossbreed(Individual other);
       * Mutate this individual
       * Mutate chromosomes of this individual; every chromosome is mutated
       * with probability set in settings of evolution.
       * This probability is supposed to be quite low number, roughly 1 %.
      protected abstract void mutate();
       * Check this individual
       * Check if this individual still suits the assignment.
       * If not, repair this individual to suit it again.
      protected abstract void check();
       * Implementation of Comparable: comparing of individuals by fitness
       * @param other Another individual to compare
      public int compareTo(Individual other)
        return this.getFitness() - other.getFitness();
    One implementation class:
    * KnapsackIndividual.java
    * Created on 21. leden 2007, 1:41
    package genetics;
    import java.util.Random;
    import java.util.TreeMap;
    import knapsack.KnapsackProblem;
    * This is practically the same as KnapsackProblem class but designed specially
    * for solving knapsack problem with genetic algorithm so all unnecessary fields
    * and methods are removed.
    * @author Richard V�tek
    * @version 1.0
    public class KnapsackIndividual extends Individual
       * Chromosomes of this individual
       * In case of knapsack problem, they are things currentl in knasack
      protected boolean[] arrChromosomes;
       * Cached value of fitness of this individual
       * Used to not to count fitness of this individual everytime when needed
       * (and it is often needed); once counted, it will be read from this cached value
      private int intFitnessCache = Integer.MIN_VALUE;
       * Randomizer for random-driven methods (like mutation, etc.)
      private Random randomizer = new Random();
       * Reference to evolution to read mutation probability from
      protected Evolution evolution;
       * Assignment of problem instance
      protected KnapsackProblem assignment;
       * Create a new Individual instance
       * @param   assignment  Object representing assignment of particular problem
       * @param   evolution   Reference to evolution object to be able to read evolution's settings from
      public KnapsackIndividual(KnapsackProblem assignment, Evolution evolution)
        this.assignment = assignment;
        this.evolution = evolution;
        this.arrChromosomes = new boolean[assignment.getNumberOfThings()];
       * Create random chromosomes for this individual
       * @see Individual#createRandomChromosomes()
      protected void createRandomChromosomes()
        int intChromosomeCount = this.arrChromosomes.length;
        for (int i = 0; i < intChromosomeCount; i++)
          this.arrChromosomes[i] = this.randomizer.nextBoolean();
       * Get fitness of this individual
       * In case of knapsack, fitness is sum of prices of all things currently in knapsack
       * @see Individual#getFitness()
      protected int getFitness()
        //if cached value exist, return it
        if (this.intFitnessCache != Integer.MIN_VALUE)
          return this.intFitnessCache;
        //otherwise, count fitness of this individual
        int intChromosomeCount = this.arrChromosomes.length;
        int intSumOfValues = 0;
        //in case of knapsack, fitness is value of all things currently in knapsack
        //(sum of values of all things in knapsack)
        for (int i = 0; i < intChromosomeCount; i++)
          intSumOfValues = this.assignment.arrPrices;
    //save counted fitness to cache
    this.intFitnessCache = intSumOfValues;
    return intSumOfValues;
    * Cross-breed two individuals
    * @param other The other individual for cross-breed
    * @return The other individual after cross-breed (but this individual is affected too)
    * @see Individual#crossbreed()
    protected Individual crossbreed(Individual other)
    int intChromosomeCount = this.arrChromosomes.length;
    //position from which on swap chromosomes of this and the other individual
    int intCrossbreedPosition = this.randomizer.nextInt(intChromosomeCount);
    boolean booTemp;
    //swap chromosomes from cross-breed position on
    for (int i = intCrossbreedPosition; i < intChromosomeCount; i++)
    booTemp = ((KnapsackIndividual) this).arrChromosomes[i];
    ((KnapsackIndividual) this).arrChromosomes[i] = ((KnapsackIndividual) other).arrChromosomes[i];
    ((KnapsackIndividual) other).arrChromosomes[i] = booTemp;
    return other;
    * Mutate individual chromosomes of this individual with certain probability
    * In case of knapsack, particular thing is just inserted/taken out of the knapsack
    * @see Individual#mutate()
    protected void mutate()
    //probability of mutation (in percents)
    int intMutationProbability = this.evolution.getMutationProbability();
    int intChromosomeCount = this.arrChromosomes.length;
    //iterate through all chromosomes, mutating them with certain (set) probability
    for (int i = 0; i < intChromosomeCount; i++)
    //mutation probability passed => mutate this chromosome
    if (this.randomizer.nextInt(100) < intMutationProbability)
    this.arrChromosomes[i] = !this.arrChromosomes[i];
    //when mutation finished, we must check if this individual still suits the assignment;
    //if not, repait it
    this.check();
    * Check if this individual still suits the assignment; if not, repair it
    * In case of knapsack it means that sum of weights of things currently in knapsack
    * will not exceed capacity of backpack; if exceeds, take out as many things as necessary
    * to not to exceed again; choose things to be taken out according to worst weight to price ratio
    * @see Individual#check()
    protected void check()
    int intSumOfWeights = 0;
    //list of things in the knapsack sorted by weight to price ratio
    //key: index of thing in knapsack
    //value: weight/price ratio
    TreeMap<Integer, Float> things = new TreeMap<Integer, Float>();
    for (int i = 0; i < this.arrChromosomes.length; i++)
    //thing in the knapsack
    if (this.arrChromosomes[i] == true)
    //add its weight to sum of weights
    intSumOfWeights += this.assignment.arrWeights[i];
    //add it to the list of things sorted by weight to price ratio
    things.put(i, (((float) this.assignment.arrWeights[i]) / ((float) this.assignment.arrPrices[i])));
    //sum of weights exceeds knapsack capacity => take out as many things as necessary
    while (intSumOfWeights > this.assignment.getKnapsackCapacity())
    //take out thing with worst weight/price ratio from all things currently in knapsack
    this.arrChromosomes[things.lastKey()] = false;
    //update sum of weights of things currently in knapsack
    intSumOfWeights -= things.get(things.lastKey());
    //also remove this thing from list of things
    things.remove(things.lastKey());
    And another class, where i need this feature (tried to use generics for that, but they can't be used in this way):
    * Evolution.java
    * Created on 21. leden 2007, 2:47
    package genetics;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Arrays;
    * Class for algorithms using simulated evolution to deal with a problem
    * Tried to be designed general enough to allow to be used for every genetic algotihm.
    * If true, only class Individual must be implemented according to problem to be solved,
    * the rest of genetic algorithm stays the same.
    * @author Richard V�tek
    * @version
    public class Evolution<Problem, IndividualClass extends Individual>
       * Number of generations of evolution to finish
      protected int intGenerationCount;
       * Number of individuals in each generation
      protected int intGenerationSize;
       * Elite individual count
       * All elite individuals are just copied from one generation to another with no change
      protected int intGenerationEliteCount;
       * Number of individuals participating a tournament
       * To select an good individual for next generation, tournaments are hold.
       * This affects number of individuals which one good individual is selected
       * from in one tournament.
       * @see <a href="http://cs.felk.cvut.cz/%7Exobitko/ga/example_f.html">Genetic Algorithm Example Applet</a>
      protected int intGenerationTournamentSize;
       * Probability of mutation (in percents)
      protected int intMutationProbability;
       * Current generation of individuals in evolution
      protected Generation<IndividualClass> thisGeneration;
       * Next generation of individuals in evolution
      protected Generation<IndividualClass> nextGeneration;
       * Fitness of best individual in this generation
      private int intIndividualBestFitness;
       * Sum of fitnesses of all individuals in this generation
      private int intIndividualsSumFitness;
       * Fitness of worst individual in this generation
      private int intIndividualWorstFitness;
       * Fitness of best elite individual in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualEliteBestFitness;
       * Sum of fitnesses of all elite individuals in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualElitesSumFitness;
       * Fitness of worst elite individual in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualEliteWorstFitness;
       * Create a new instance of Evolution (settings passed through parameters)
       * @param   intGenerationCount            Number of generation of evolution to finish
       * @param   intGenerationSize             Number of individuals in each generation
       * @param   intGenerationEliteRatio       Elite individuals to generation size ratio (in percents)
       * @param   intGenerationTournamentRatio  Members of tournament to generation size ratio (in percents)
       * @param   intMutationProbability        Probability of mutation of each chromosome of each individual of generation (in percents)
       * @see     #intGenerationEliteCount
       * @see     #intGenerationTournamentSize
      public Evolution(
        int intGenerationCount, int intGenerationSize,
        int intGenerationEliteRatio, int intGenerationTournamentRatio,
        int intMutationProbability)
        this.intGenerationCount = intGenerationCount;
        this.intGenerationSize = intGenerationSize;
        this.intGenerationEliteCount = (int) (intGenerationSize * (intGenerationEliteRatio / 100.0));
        this.intGenerationTournamentSize = (int) (intGenerationSize * (intGenerationTournamentRatio / 100.0));
        this.intMutationProbability = intMutationProbability;
       * Create a new instance of Evolution (settings loaded from settings file)
       * @param   strSettingFile  Name of file containing settings for evolution
       * @throws  IOException     File does not exist, cannot be read, etc.
       * @throws  Exception       Another exception occured during loading of file
      public Evolution(String strSettingFile)
        BufferedReader settings;
        String settingsLine;
        int intLineCounter = 0;
        int intSetting;
        try
          settings = new BufferedReader(new FileReader(strSettingFile));
          while ((settingsLine = settings.readLine()) != null)
            intLineCounter++;
            settingsLine = settingsLine.substring(0, settingsLine.indexOf("\t"));
            intSetting = Integer.parseInt(settingsLine);
            switch (intLineCounter)
              case 1:
                this.intGenerationCount = intSetting;
                break;
              case 2:
                this.intGenerationSize = intSetting;
                break;
              case 3:
                this.intGenerationEliteCount = (int) (this.intGenerationSize * (intSetting / 100.0));
                break;
              case 4:
                this.intGenerationTournamentSize = (int) (this.intGenerationSize * (intSetting / 100.0));
                break;
              case 5:
                this.intMutationProbability = intSetting;
                break;
            } //switch
          } //while
          //after reading has been completed, let's close the stream
          settings.close();
        } //try
        //IO exception - file not found, cannot be read, etc.
        catch (IOException ioe)
          System.out.println("Vyskytl se I/O probl�m p&#345;i na&#269;�t�n� zad�n� ze souboru " + strSettingFile);
        //Exception - another problem during reading of file
        catch (Exception e)
          System.out.printf("Vyskytl se n&#283;jak� divn� probl�m p&#345;i na&#269;�t�n� zad�n� ze souboru %s. V�pis vyj�mky:\n", strSettingFile);
          e.printStackTrace();
       * Vivify first generation for evolution
       * Necessary number of individuals is created with random chromosomes.
       * Their chromosomes must then be checked if they suit the assignment
       * and if not so, repaired.
      private Generation<IndividualClass> vivifyFirstGeneration()
        //create a brand-new generation
        Generation generation = new Generation<IndividualClass>(this);
        int intTemp;
        //for all individual of this generation
        for (int i = 0; i < this.intGenerationSize; i++)
    //create an individual with no chromosomes
    generation.arrIndividuals[i] = new IndividualClass(this, Problem);
          //create a set of random chromosomes
          neration.arrIndividuals.createRandomChromosomes();
    //if these chromosomes does not suit assignment, repair them
    generation.arrIndividuals[i].check();
    //sort Individuals by fitness so elite individuals get to first positions of array
    Arrays.sort(generation.arrIndividuals);
    //now count statistics for elite individuals (it is enough to count them once,
    //elite don't get changed so their statistics don't get changed either)
    this.intIndividualEliteBestFitness = Integer.MIN_VALUE;
    this.intIndividualElitesSumFitness = 0;
    this.intIndividualEliteWorstFitness = Integer.MAX_VALUE;
    //count statistics for elite individuals
    for (int i = 0; i < this.intGenerationEliteCount; i++)
    intTemp = generation.arrIndividuals[i].getFitness();
    //better fitness than best fitness so far
    if (intTemp > this.intIndividualEliteBestFitness)
    this.intIndividualEliteBestFitness = intTemp;
    //worse fitness than worst fitness so far
    else if (intTemp < this.intIndividualEliteWorstFitness)
    this.intIndividualEliteWorstFitness = intTemp;
    this.intIndividualElitesSumFitness += intTemp;
    //reset generation's statistics
    this.intIndividualBestFitness = this.intIndividualEliteBestFitness;
    this.intIndividualsSumFitness = this.intIndividualElitesSumFitness;
    this.intIndividualWorstFitness = this.intIndividualEliteWorstFitness;
    //count generation's statistics also from rest of individuals
    for (int i = this.intGenerationEliteCount; i < this.intGenerationSize; i++)
    updateGenerationStatistics(generation.arrIndividuals[i].getFitness());
    return generation;
    * Get next generation in evolution
    * Core method for all evolution; Through this method, new generation is obtained.
    * Every next generation should contain better individuals than the previous one
    * (till certain point) so with growing number of iterations in evolution, we
    * get better results (till certain point).
    * Everytime all elite individuals are copied to next generation, then hold needed number of
    * tournaments to choose a pair of good-looking individuals, cross-breed individuals in these
    * pairs, mutate them (and repair if necessary) and finally add to next generation.
    * @return Generation Next generation in evolution
    * @see Generation#tournament()
    * @see Generation#crossbreed()
    * @see Generation#mutate()
    private Generation getNextGeneration()
    Generation nextGeneration = new Generation(this);
    //number of pairs of individuals to select for next generation
    int intIndividualPairsToSelect = (this.intGenerationSize - this.intGenerationEliteCount) / 2;
    int intTemp;
    //reset generation's statistics
    this.intIndividualBestFitness = this.intIndividualEliteBestFitness;
    this.intIndividualsSumFitness = this.intIndividualElitesSumFitness;
    this.intIndividualWorstFitness = this.intIndividualEliteWorstFitness;
    //just copy all elite individuals from this generation to another
    //(they are on first positions of array of individuals)
    for (int i = 0; i < this.intGenerationEliteCount; i++)
    nextGeneration.arrIndividuals[i] = this.thisGeneration.arrIndividuals[i];
    //hold as many tournaments as necessary to select remaining number of pairs
    //of good-looking individuals for next generation (apart from the elite ones)
    for (int i = 0; i < intIndividualPairsToSelect; i++)
    this.thisGeneration.tournament();
    this.thisGeneration.crossbreed();
    this.thisGeneration.mutate();
    //add this individual in next generation
    nextGeneration.arrIndividuals[2 * i] = this.thisGeneration.nextGenerationIndividual01;
    //update statistics of generation
    updateGenerationStatistics(this.thisGeneration.nextGenerationIndividual01.getFitness());
    //add this individual in next generation
    nextGeneration.arrIndividuals[2 * i + 1] = this.thisGeneration.nextGenerationIndividual02;
    //update statistics of generation
    updateGenerationStatistics(this.thisGeneration.nextGenerationIndividual02.getFitness());
    //next generation is complete => return it
    return nextGeneration;
    * Update statistics of current generations
    * @param intFitness Fitness that may possibly update generation's statistics
    * (best fitness, worst fitness, sum of fitnesses)
    private void updateGenerationStatistics(int intFitness)
    //better fitness than best fitness so far
    if (intFitness > this.intIndividualBestFitness)
    this.intIndividualBestFitness = intFitness;
    //worse fitness than worst fitness so far
    else if (intFitness < this.intIndividualWorstFitness)
    this.intIndividualWorstFitness = intFitness;
    //update sum of fitnesses as well (for average fitness)
    this.intIndividualsSumFitness += intFitness;
    * Execute evolution process
    * Vivify first generation and then as many next generations as set in settings of evolution
    public void evolution()
    this.thisGeneration = vivifyFirstGeneration();
    //output generation's statistics
    System.out.printf("Generace 0:\t%d\t%d\t%d", this.getIndividualBestFitness(), this.getIndividualAverageFitness(), this.getIndividualWorstFitness());
    for (int i = 0; i < this.intGenerationCount; i++)
    this.nextGeneration = getNextGeneration();
    this.thisGeneration = this.nextGeneration;
    //output generation's statistics
    System.out.printf("Generace %d:\t%d\t%d\t%d", i, this.getIndividualBestFitness(), this.getIndividualAverageFitness(), this.getIndividualWorstFitness());
    * Get best fitness of all individuals in this generation
    public int getIndividualBestFitness()
    return intIndividualBestFitness;
    * Get average fitness of all individuals in this generation
    public float getIndividualAverageFitness()
    return (this.intIndividualsSumFitness / (float) this.intGenerationSize);
    * Get worst fitness of all individuals in this generation
    public int getIndividualWorstFitness()
    return intIndividualWorstFitness;
    * Get probability of mutation
    * @return Probability of mutation of each chromosome of every individual in generation (in percents)
    public int getMutationProbability()
    return intMutationProbability;

  • ".. is an abstract class.  It can't be instantiated"

    Does anyone have an idea of how I can get rid of the above error message? Here is a bit of my code:
    import java.io.*;
    import java.util.Vector;
    class Project3 {
    private BiTree company = new BiTree();
    public static void main(String[] args) throws IOException {
    Project3 run = new Project3();
    run.Command();
    public void Command() throws IOException {}
    public interface comparable {
    //not sure if need this in this class, or at all
    public int compare(Object object1,Object object2);
    public void add() {
    Employee newOne = new Employee();
    System.out.println("Enter name");
    BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
    String name = stdin.readLine();
    System.out.println("Enter title");
    BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
    String title = stdin.readLine();
    System.out.println("Enter payrate");
    BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
    payrate = Double.parseDouble.stdin.readLine();
    newOne.setTitle(title);
    newOne.setName(name);
    newOne.setPayrate(payrate);
    company.insert(newOne);
    }

    It is not possible to create instances of an abstract class.
    I hope this example helps,
    abstract class Vehicle
    public static void main(String arg[])
    Vehicle a;
    a = new Automobile(); // ok, since Automobile is a kind of Vehicle
    // The class Automobile, a special case of Vehicle
    class Automobile extends Vehicle

  • Sort Linked List...

    I need help sorting a linked list.
    So far, in my sort method I have...
    public LinkedList sort();
    LinkedList newList = new LinkedList();
    Node ref;
    Node temp = new Node(head.getempID(); head.getempLast(), head.getempFirst(); head.getempDept(), head.getempSalary());
    for(ref = head; ref != null; ref.getNext());
    if(ref.getempID() <= temp.getEmpID());
    temp = (ref.getempID(), ref.getempLast(), ref.getempFirst(), ref.getempDept(), ref.getempSalary());
    newList.insert(temp); //???????
    return newList();
    // As you can tell, each one of my node's consists of an employee's id number, last name, first name, department, and salary...I need to sort the linked list by the employee's ID number. I can not figure out how to swap nodes though. PLEASE HELP A KID OUT!!!

    I was worng, my last data structure lecture today(I hope).
          |       |     |       |     |       |     |       |         |       |
    head->| Node1 |---->| Node2 |---->| Node3 |---->| Node4 |---etc-->| NodeN |->null
          |       |     |       |     |       |     |       |         |       |
    Q: How do you swap node2 with node3?
    A: Think about it!  Look at a picture if thats what you need. Draw the lines of reference to figure it out.
      1. Where does node1.next need to point to, how about node2.next, or node3.next?
      3. How do you change these without losing a node, are you going to need a temp?
      4. What about special case(switching node1 and node2)?
    This is simple problem solving skills.  I assume you have built the list yourself,
    so you have the basic knowledge base needed.

  • Can someone help with splitting a Linked List.??

    Any help would be awesome!!!
    My code just will not work!! Any help would be appreciated! My problem is in the last method SplitAt. These are the conditions set and my code:
    Splitting a Linked List at a Given Node, into Two Sublists
    a. Add the following as an abstract method to the class
    LinkedListClass:
    public void splitAt (LinkedListClass<T> secondList, T item);
    //This method splits the list at the node with the info item into two sublists.
    //Precondition: The list must exist.
    //Postcondition: first and last point to the first and last nodes of the first sublist,
    // respectively. secondList.first and secondList.last point to the first
    // and last nodes of the second sublist.
    Consider the following statements:
    UnorderedLinkedList<Integer> myList;
    UnorderedLinkedList<Integer> otherList;
    Suppose myList points to the list with the elements 34, 65, 18, 39, 27, 89, and 12 (in this order). The statement
    myList.splitAt(otherList, 18);
    splits myList into two sublists: myList points to the list with elements 34 and 65, and otherList points to the sublist with elements 18, 39, 27, 89, and 12.
    b. Provide the definition of the method splitAt in the class UnorderedLinkedList. Also write a program to test your method.
    public class UnorderedLinkedList<T> extends LinkedListClass<T>
           //Default constructor
        public UnorderedLinkedList()
            super();
            //Method to determine whether searchItem is in
            //the list.
            //Postcondition: Returns true if searchItem is found
            //               in the list; false otherwise.
        public boolean search(T searchItem)
            LinkedListNode<T> current; //variable to traverse
                                       //the list
            boolean found;
            current = first;  //set current to point to the first
                              //node in the list
            found = false;    //set found to false
            while (current != null && !found) //search the list
                if (current.info.equals(searchItem)) //item is found
                    found = true;
                else
                   current = current.link; //make current point to
                                           //the next node
            return found;
            //Method to insert newItem in the list.
            //Postcondition: first points to the new list
            //               and newItem is inserted at the
            //               beginning of the list. Also,
            //               last points to the last node and
            //               count is incremented by 1.
        public void insertFirst(T newItem)
            LinkedListNode<T> newNode;     //variable to create the
                                        //new node
            newNode =
               new LinkedListNode<T>(newItem, first); //create and
                                           //insert newNode before
                                           //first
            first = newNode;   //make first point to the
                               //actual first node
            if (last == null)   //if the list was empty, newNode is
                                //also the last node in the list
                last = newNode;
            count++;     //increment count
            //Method to insert newItem at the end of the list.
            //Postcondition: first points to the new list and
            //               newItem is inserted at the end
            //               of the list. Also, last points to
            //               the last node and
            //               count is incremented by 1.
        public void insertLast(T newItem)
            LinkedListNode newNode; //variable to create the
                                    //new node
            newNode =
               new LinkedListNode(newItem, null);  //create newNode
            if (first == null)  //if the list is empty, newNode is
                                //both the first and last node
                first = newNode;
                last = newNode;
            else     //if the list is not empty, insert
                     //newNode after last
                last.link = newNode; //insert newNode after last
                last = newNode;      //set last to point to the
                                     //actual last node
            count++;
        }//end insertLast
            //Method to delete deleteItem from the list.
            //Postcondition: If found, the node containing
            //               deleteItem is deleted from the
            //               list. Also, first points to the first
            //               node, last points to the last
            //               node of the updated list, and count
            //               is decremented by 1.
        public void deleteNode(T deleteItem)
            LinkedListNode<T> current; //variable to traverse
                                       //the list
            LinkedListNode<T> trailCurrent; //variable just
                                            //before current
            boolean found;
            if ( first == null)    //Case 1; the list is empty
                System.err.println("Cannot delete from an empty "
                                 + "list.");
            else
                if (first.info.equals(deleteItem)) //Case 2
                    first = first.link;
                       if (first == null)  //the list had only one node
                          last = null;
                       count--;
                else  //search the list for the given info
                    found = false;
                    trailCurrent = first; //set trailCurrent to
                                          //point to the first node
                    current = first.link; //set current to point to
                                          //the second node
                    while (current != null && !found)
                        if (current.info.equals(deleteItem))
                            found = true;
                        else
                            trailCurrent = current;
                            current = current.link;
                    }//end while
                    if (found) //Case 3; if found, delete the node
                        count--;
                        trailCurrent.link = current.link;
                        if (last == current)  //node to be deleted
                                              //was the last node
                           last = trailCurrent;  //update the value
                                                 //of last
                    else
                       System.out.println("Item to be deleted is "
                                        + "not in the list.");
                }//end else
            }//end else
        }//end deleteNode
        public void splitAt(LinkedListClass<T> secondList, T item)
         LinkedListNode<T> current;
         LinkedListNode<T> trailCurrent;
         int i;
         boolean found;
         if (first==null)
        System.out.println("Empty.");
        first=null;
        last=null;
        count--;
         else
              current=first;
              found=false;
              i=1;
              while(current !=null &&!found)
                   if(current.info.equals(secondList))
                       found= true;
                       else
                            trailCurrent=current;
                            i++;
              if(found)
                   if(first==current)
                        first=first;
                        last=last;
                        count=count;
                        count=0;
                   else
                        first=current;
                        last=last;
                        last=null;
                        count = count- i+1;
                        count = i-1;
                   else
                        System.out.println("Item to be split at is "
                             + "not in the list.");
                   first=null;
                   last=null;
                   count=0;
        }Edited by: romeAbides on Oct 10, 2008 1:24 PM

    I dont have a test program at all. The program is supposed to prompt for user input of numbers. (it does) Take the input and end at input of -999 (it does). Then it asks user where it wants to split list (it does). When I enter a number it does nothing after that. I am going to post updated code and see if that helps along with all the classes. Thanks!
    This is the class to prompt:
    import java.util.*;
    public class Ch16_ProgEx6
        static Scanner console = new Scanner(System.in);
         public static void main(String[] args)
             UnorderedLinkedList<Integer> list
                              = new UnorderedLinkedList<Integer>();
            UnorderedLinkedList<Integer> subList =
                              new UnorderedLinkedList<Integer>();
             Integer num;
             System.out.println("Enter integers ending with -999.");
             num = console.nextInt();
             while (num != -999)
                 list.insertLast(num);
                 num = console.nextInt();
            System.out.println();
            System.out.println("list: ");
            list.print();
            System.out.println();
            System.out.println("Length of list: " + list.length());
            System.out.print("Enter the number at which to split list: ");
            num = console.nextInt();
            list.splitAt(subList, num);
            System.out.println("Lists after splitting list");
            System.out.print("list: ");
            list.print();
            System.out.println();
            System.out.println("Length of list: " + list.length());
            System.out.print("sublist: ");
            subList.print();
            System.out.println();
            System.out.println("Length of sublist: " + subList.length());
    }This is the ADT:
    public interface LinkedListADT<T> extends Cloneable
        public Object clone();
           //Returns a copy of objects data in store.
           //This method clones only the references stored in
           //each node of the list. The objects that the
           //list nodes point to are not cloned.
        public boolean isEmptyList();
           //Method to determine whether the list is empty.
           //Postcondition: Returns true if the list is empty;
           //               false otherwise.
        public void initializeList();
           //Method to initialize the list to an empty state.
           //Postcondition: The list is initialized to an empty
           //               state.
        public void print();
           //Method to output the data contained in each node.
        public int length();
           //Method to return the number of nodes in the list.
           //Postcondition: The number of nodes in the list is
           //               returned.
        public T front();
           //Method to return a reference of the object containing
           //the data of the first node of the list.
           //Precondition: The list must exist and must not be empty.
           //Postcondition: The reference of the object that
           //               contains the info of the first node
           //               is returned.
        public T back();
           //Method to return a reference of object containing
           //the data of the last node of the list.
           //Precondition: The list must exist and must not be empty.
           //Postcondition: The reference of the object that
           //               contains the info of the last node
           //               is returned.
        public boolean search(T searchItem);
           //Method to determine whether searchItem is in the list.
           //Postcondition: Returns true if searchItem is found
           //               in the list; false otherwise.
        public void insertFirst(T newItem);
           //Method to insert newItem in the list.
           //Postcondition: newItem is inserted at the
           //               beginning of the list.
        public void insertLast(T newItem);
           //Method to insert newItem at the end of the list.
           //Postcondition: newItem is inserted at the end
           //               of the list.
        public void deleteNode(T deleteItem);
           //Method to delete deleteItem from the list.
           //Postcondition: If found, the node containing
           //               deleteItem is deleted from the
           //               list.
        public void splitAt(LinkedListClass<T> secondList, T item);
    }This is the linked list class:
    import java.util.NoSuchElementException;
    public abstract class LinkedListClass<T> implements LinkedListADT<T>
        protected class LinkedListNode<T> implements Cloneable
            public T info;
            public LinkedListNode<T> link;
               //Default constructor
               //Postcondition: info = null; link = null;
            public LinkedListNode()
                info = null;
                link = null;
               //Constructor with parameters
               //This method sets info pointing to the object to
               //which elem points to and link is set to point to
               //the object to which ptr points to.
               //Postcondition:  info = elem; link = ptr;
            public LinkedListNode(T elem, LinkedListNode<T> ptr)
                info = elem;
                link = ptr;
               //Returns a copy of objects data in store.
               //This method clones only the references stored in
               //the node. The objects that the nodes point to
               //are not cloned.
            public Object clone()
                LinkedListNode<T> copy = null;
                try
                    copy = (LinkedListNode<T>) super.clone();
                catch (CloneNotSupportedException e)
                    return null;
                return copy;
               //Method to return the info as a string.
               //Postcondition: info as a String object is
               //               returned.
            public String toString()
                return info.toString();
        } //end class LinkedListNode
        public class LinkedListIterator<T>
            protected LinkedListNode<T> current;  //variable to
                                                  //point to the
                                                  //current node in
                                                  //list
            protected LinkedListNode<T> previous; //variable to
                                                  //point to the
                                                  //node before the
                                                  //current node
               //Default constructor
               //Sets current to point to the first node in the
               //list and sets previous to null.
               //Postcondition: current = first; previous = null;
            public LinkedListIterator()
                current = (LinkedListNode<T>) first;
                previous = null;
               //Method to reset the iterator to the first node
               //in the list.
               //Postcondition: current = first; previous = null;
            public void reset()
                current = (LinkedListNode<T>) first;
                previous = null;
               //Method to return a reference of the info of the
               //current node in the list and to advance iterator
               //to the next node.
               //Postcondition: previous = current;
               //               current = current.link;
               //               A refrence of the current node
               //               is returned.
            public T next()
                if (!hasNext())
                    throw new NoSuchElementException();
                LinkedListNode<T> temp = current;
                previous = current;
                current = current.link;
                return temp.info;
                //Method to determine whether there is a next
                //element in the list.
                //Postcondition: Returns true if there is a next
                //               node in the list; otherwise
                //               returns false.
            public boolean hasNext()
                return (current != null);
               //Method to remove the node currently pointed to
               //by the iterator.
               //Postcondition: If iterator is not null, then the
               //               node that the iterator points to
               //               is removed. Otherwise the method
               //               throws NoSuchElementException.
            public void remove()
                if (current == null)
                    throw new NoSuchElementException();
                if (current == first)
                    first = first.link;
                    current = (LinkedListNode<T>) first;
                    previous = null;
                    if (first == null)
                        last = null;
                else
                    previous.link = current.link;
                    if (current == last)
                        last = first;
                        while (last.link != null)
                            last = last.link;
                    current = current.link;
                count--;
               //Method to return the info as a string.
               //Postcondition: info as a String object is returned.
            public String toString()
                return current.info.toString();
        } //end class LinkedListIterator
           //Instance variables of the class LinkedListClass
        protected LinkedListNode<T> first; //variable to store the
                                           //address of the first
                                           //node of the list
        protected LinkedListNode<T> last;  //variable to store the
                                           //address of the last
                                           //node of the list
        protected int count;  //variable to store the number of
                              //nodes in the list
           //Default constructor
           //Initializes the list to an empty state.
           //Postcondition: first = null, last = null,
           //               count = 0
        public LinkedListClass()
            first = null;
            last = null;
            count = 0;
           //Method to determine whether the list is empty.
           //Postcondition: Returns true if the list is empty;
           //               false otherwise.
        public boolean isEmptyList()
            return (first == null);
           //Method to initialize the list to an empty state.
           //Postcondition: first = null, last = null,
           //               count = 0
        public void initializeList()
            first = null;
            last = null;
            count = 0;
           //Method to output the data contained in each node.
        public void print()
            LinkedListNode<T> current; //variable to traverse
                                       //the list
            current = first;    //set current so that it points to
                                //the first node
            while (current != null) //while more data to print
                System.out.print(current.info + " ");
                current = current.link;
        }//end print
           //Method to return the number of nodes in the list.
           //Postcondition: The value of count is returned.
        public int length()
            return count;
           //Method to return a reference of the object containing
           //the data of the first node of the list.
           //Precondition: The list must exist and must not be empty.
           //Postcondition: The reference of the object that
           //               contains the info of the first node
           //               is returned.
        public T front()
            return first.info;
            //Method to return a reference of object containing
            //the data of the last node of the list.
            //Precondition: The list must exist and must not be empty.
            //Postcondition: The reference of the object that
            //               contains the info of the last node
            //               is returned.
        public T back()
            return last.info;
           //Returns a copy of objects data in store.
           //This method clones only the references stored in
           //each node of the list. The objects that the
           //list nodes point to are not cloned.
        public Object clone()
            LinkedListClass<T> copy = null;
            try
                copy = (LinkedListClass<T>) super.clone();
            catch (CloneNotSupportedException e)
                return null;
                //If the list is not empty clone each node of
                //the list.
            if (first != null)
                   //Clone the first node
                copy.first = (LinkedListNode<T>) first.clone();
                copy.last = copy.first;
                LinkedListNode<T> current;
                if (first != null)
                    current = first.link;
                else
                    current = null;
                   //Clone the remaining nodes of the list
                while (current != null)
                    copy.last.link =
                            (LinkedListNode<T>) current.clone();
                    copy.last = copy.last.link;
                    current = current.link;
            return copy;
           //Method to return an iterator of the list.
           //Postcondition: An iterator is instantiated and
           //               returned.
        public LinkedListIterator<T> iterator()
            return new LinkedListIterator<T>();
           //Method to determine whether searchItem is in
           //the list.
           //Postcondition: Returns true if searchItem is found
           //               in the list; false otherwise.
        public abstract boolean search(T searchItem);
           //Method to insert newItem in the list.
           //Postcondition: first points to the new list
           //               and newItem is inserted at the
           //               beginning of the list. Also,
           //               last points to the last node and
           //               count is incremented by 1.
        public abstract void insertFirst(T newItem);
           //Method to insert newItem at the end of the list.
           //Postcondition: first points to the new list and
           //               newItem is inserted at the end
           //               of the list. Also, last points to
           //               the last node and
           //               count is incremented by 1.
        public abstract void insertLast(T newItem);
           //Method to delete deleteItem from the list.
           //Postcondition: If found, the node containing
           //               deleteItem is deleted from the
           //               list. Also, first points to the first
           //               node, last points to the last
           //               node of the updated list, and count
           //               is decremented by 1.
        public abstract void deleteNode(T deleteItem);
        public abstract void splitAt(LinkedListClass<T> secondList, T item);
    }And this is the UnorderedLinked Class with the very last method the one being Im stuck on. The SplitAt Method.
    public class UnorderedLinkedList<T> extends LinkedListClass<T>
           //Default constructor
        public UnorderedLinkedList()
            super();
            //Method to determine whether searchItem is in
            //the list.
            //Postcondition: Returns true if searchItem is found
            //               in the list; false otherwise.
        public boolean search(T searchItem)
            LinkedListNode<T> current; //variable to traverse
                                       //the list
            boolean found;
            current = first;  //set current to point to the first
                              //node in the list
            found = false;    //set found to false
            while (current != null && !found) //search the list
                if (current.info.equals(searchItem)) //item is found
                    found = true;
                else
                   current = current.link; //make current point to
                                           //the next node
            return found;
            //Method to insert newItem in the list.
            //Postcondition: first points to the new list
            //               and newItem is inserted at the
            //               beginning of the list. Also,
            //               last points to the last node and
            //               count is incremented by 1.
        public void insertFirst(T newItem)
            LinkedListNode<T> newNode;     //variable to create the
                                        //new node
            newNode =
               new LinkedListNode<T>(newItem, first); //create and
                                           //insert newNode before
                                           //first
            first = newNode;   //make first point to the
                               //actual first node
            if (last == null)   //if the list was empty, newNode is
                                //also the last node in the list
                last = newNode;
            count++;     //increment count
            //Method to insert newItem at the end of the list.
            //Postcondition: first points to the new list and
            //               newItem is inserted at the end
            //               of the list. Also, last points to
            //               the last node and
            //               count is incremented by 1.
        public void insertLast(T newItem)
            LinkedListNode newNode; //variable to create the
                                    //new node
            newNode =
               new LinkedListNode(newItem, null);  //create newNode
            if (first == null)  //if the list is empty, newNode is
                                //both the first and last node
                first = newNode;
                last = newNode;
            else     //if the list is not empty, insert
                     //newNode after last
                last.link = newNode; //insert newNode after last
                last = newNode;      //set last to point to the
                                     //actual last node
            count++;
        }//end insertLast
            //Method to delete deleteItem from the list.
            //Postcondition: If found, the node containing
            //               deleteItem is deleted from the
            //               list. Also, first points to the first
            //               node, last points to the last
            //               node of the updated list, and count
            //               is decremented by 1.
        public void deleteNode(T deleteItem)
            LinkedListNode<T> current; //variable to traverse
                                       //the list
            LinkedListNode<T> trailCurrent; //variable just
                                            //before current
            boolean found;
            if ( first == null)    //Case 1; the list is empty
                System.err.println("Cannot delete from an empty "
                                 + "list.");
            else
                if (first.info.equals(deleteItem)) //Case 2
                    first = first.link;
                       if (first == null)  //the list had only one node
                          last = null;
                       count--;
                else  //search the list for the given info
                    found = false;
                    trailCurrent = first; //set trailCurrent to
                                          //point to the first node
                    current = first.link; //set current to point to
                                          //the second node
                    while (current != null && !found)
                        if (current.info.equals(deleteItem))
                            found = true;
                        else
                            trailCurrent = current;
                            current = current.link;
                    }//end while
                    if (found) //Case 3; if found, delete the node
                        count--;
                        trailCurrent.link = current.link;
                        if (last == current)  //node to be deleted
                                              //was the last node
                           last = trailCurrent;  //update the value
                                                 //of last
                    else
                       System.out.println("Item to be deleted is "
                                        + "not in the list.");
                }//end else
            }//end else
        }//end deleteNode
        public void splitAt(LinkedListClass<T> secondList, T item)
         LinkedListNode<T> current;
         LinkedListNode<T> trailCurrent;
         int i;
         boolean found;
         if (first==null)
        System.out.println("Empty.");
        first=null;
        last=null;
        count--;
        count=0;
         else
              current=first;
              found=false;
              i=1;
              while(current !=null &&!found)
                   if(current.info.equals(item))
                       found= true;
                       else
                            trailCurrent=first;
                            current=first;
                            i++;
              if(found)
                   if(first==current)
                        first.link=first;
                        last.link=last;
                           count--;
                        count=0;
                   else
                        first.link=current;
                        last.link=last;
                        last=null;
                        count = count- i+1;
                        count = i-1;
              } else  {
                  System.out.println("Item to be split at is "
                    + "not in the list.");
                   first=null;
                   last=null;
                   count=0;
        Any help or just advice would be fine. Im not the best at Java, better at VB. Am completely stumped! Thanks so much!

Maybe you are looking for

  • N95 doesn't differentiate between numbers

    Hi Everyone, I noticed an issue with most of the symbian phones that i own from nokia, which is that the phone doesn't differentiate between 2 or more numbers that are stored in the phone book, and have the same last 6 digits. for example: (+xxx) 555

  • Why do we need material specification for transfering results to class char.

    Hi, Can you guys tell me why do we need to create material specification if we want to transfer quality inspection results to a batch class? Basically I have done the following: -Create Class Characteristic -Assign the Class Characteristic to a batch

  • Internal table declaration

    What is the difference between 'OCCURS 0' addition and 'INITIAL SIZE' . CASE I :(Declaration With 'OCCURS 0' addition) DATA:BEGIN OF I_TAB OCCURS 0,        NAME(5) TYPE C,        AGE(2) TYPE C,      END OF I_TAB. CASE II :(Declartion with inital size

  • New releases: Adobe Lens Profile Creator v1.0.4 and Adobe Lens Profile Downloader v 1.0.1

    Along with last night's ACR 7.2/LR4.2 release (see the Lightroom Journal blog here: http://blogs.adobe.com/lightroomjournal/), the Adobe Lens Profile Creator and Adobe Lens Profile Downlader also got a refresh. They have now officially moved out of t

  • Ipod 2009 160gb wont turn off

    I have the late model 160gb ipod classic and one day I went to play the music and the settings went back to the original (no shuffle or repeat). Since that time the ipod will not turn off.  If I press the menu and select buttons that does not work.