LinkedList & Array mplementation

I am coding a program and i have an interface for a doubly linked list. Below are 2 parts which r giving me problems.
(1) The array-based implementation:
The implementation should be robust in that the list grows until an OutOfMemory error occurs. I did a small part of itL:
public class DoublyLinkedListImpl implements SimpleLinkedList {
public DoublyLinkedListImpl() {
     array_impl = new Object[size];
private void resize() {
Object[ ] temp = new Object[array_impl.length * 2]; // double the size
     //*** copy array_impl stuff to temp: see java.utils.Arrays for help
array_impl = temp;
private static final int size = 8; //*** initial size and resize amount
private Object[ ] array_impl;
The add methods could call resize as needed. This hides the implementation details from the user.
As the implementation of an ADT, this implementation should exposes to the user only (a) constructors and (b) the public methods specified in the interface.
(2) a test program: This tests the implementation & tries to break the implementation by trying to fetch the non-existent predecessor or successor of a node.
A brief idea of this part:
// The implementing class should provide
// -- a no-arg constructor to construct an empty list
// -- a 1-arg constructor to construct a list with one Object
// -- a 1-arg constructor to construct a list from an Object[ ]
// The implementing class must not
// -- extend a class that implements java.util.List
// -- have fields of a class type that implements java.util.List
// The standard classes that implement java.util.List are
// AbstractList ArrayList LinkedList Vector
// In short, the underlying implementation should be array based.
public abstract interface SimpleLinkedList {
// check whether empty: true if so, false otherwise
public abstract boolean isEmpty();
// get the current node's predecessor, if any: null if none
public abstract Object getPredecessor();
// get the current node's successor, if any: null if none
public abstract Object getSuccessor();
// remove 1st item: true if so, false otherwise
public abstract boolean remove(Object obj);
// remove Nth item: true if so, false otherwise
// remaining items shifted as appropriate
public abstract boolean remove(int n);
// remove all: two signatures, same semantics
public abstract void remove();
public abstract void clear();
// get Nth item: null returned in case of failure
public abstract Object getNth(int n);
// add an item at the end
public abstract void add(Object obj);
// add an item at a specified position: false if bad position
// If the position is bad, item is added to the end.
// Current items are shifted as appropriate.
public abstract boolean add(Object obj, int position);
// return the list as an array (perhaps empty) of Objects
// Changing the returned Object array should not
// change the SimpleLinkedList from which the array was derived.
public abstract Object[ ] toArray();
// traverse the list, printing to the standard output
// the toString value of every Object therein
public abstract void traverse();
}

I think this is what you need (I always only increase or decrease the size by 1, so no resize-method is needed).
public class DoublyLinkedListImpl implements SimpleLinkedList
  private Object[ ] array;
  protected int pos = -1; // current position of "window" on List
  // position -1 means that the array/list is isEmpty
  public DoublyLinkedListImpl()
    array = null;
  public DoublyLinkedListImpl(Object obj)
    add(obj);
  public DoublyLinkedListImpl(Object[] obj_array)
    array = new Object[obj_array.length];
    System.arraycopy(obj_array, 0, array, 0, obj_array.length);
    pos = 0;
  // check whether empty: true if so, false otherwise
  public boolean isEmpty()
    if (pos == -1 || array == null) return true;
    return false;
  // get the current node's predecessor, if any: null if none
  public Object getPredecessor()
    if (pos==0) return null;
    return array[--pos];
  // get the current node's successor, if any: null if none
  public Object getSuccessor()
    if (pos == array.length-1) return null;
    return array[++pos];
  // remove 1st item: true if so, false otherwise
  public boolean remove(Object obj)
    if (isEmpty()) return false;
    if (array.length==1) clear();
    Object[ ] temp = array;
    array = new Object[array.length - 1];
    System.arraycopy(temp, 1, array, 0, array.length);
    return true;
  // remove Nth item: true if so, false otherwise
  // remaining items shifted as appropriate
  public boolean remove(int n)
    if (n==0) { remove(null); return true; }
    if (n<0 || n>array.length-1) return false;
    if (pos>=n) --pos;
    Object[ ] temp = array;
    array = new Object[array.length - 1];
    System.arraycopy(temp, 0, array, 0, n);
    if (n==array.length) return true;
    System.arraycopy(temp, n+1, array, n, array.length-n);
    return true;
  // remove all: two signatures, same semantics
  public void remove()
    array = null;
    pos = -1;
  public void clear()
    remove();
  // get Nth item: null returned in case of failure
  public Object getNth(int n)
    if (isEmpty() || n<0 || n>array.length-1) return null;
    pos = n;
    return array[n];
  // add an item at the end
  public void add(Object obj)
    if (isEmpty())
      array = new Object[1];
      array[0] = obj;
      pos = 0;
      return;
    // resize
    Object[ ] temp = array;
    array = new Object[array.length + 1];
    System.arraycopy(temp, 0, array, 0, temp.length);
    // add
    array[array.length-1] = obj;
    pos = array.length-1;
  // add an item at a specified position: false if bad position
  // If the position is bad, item is added to the end.
  // Current items are shifted as appropriate.
  public boolean add(Object obj, int position)
    if (position<0 || position>array.length-1) { add(obj); return false; }
    pos=position;
    // resize
    Object[ ] temp = array;
    array = new Object[array.length + 1];
    System.arraycopy(temp, 0, array, 0, position);
    array[position] = obj;
    System.arraycopy(temp, position, array, position+1, temp.length-position);
    return true;
  // return the list as an array (perhaps empty) of Objects
  // Changing the returned Object array should not
  // change the SimpleLinkedList from which the array was derived.
  public Object[ ] toArray()
    if (isEmpty()) return null;
    return (Object[]) array.clone();
  // traverse the list, printing to the standard output
  // the toString value of every Object therein
  public void traverse()
    if (isEmpty()) System.out.println("null");
    else for (int i=0; i<array.length; ++i) System.out.println(array);
// for testing purposes only
public static void main(String[] args)
Integer a = new Integer(3), b = new Integer(4), c = new Integer(5);
DoublyLinkedListImpl dlli = new DoublyLinkedListImpl();
System.out.println("Position: "+dlli.pos);
dlli = new DoublyLinkedListImpl(b);
dlli.traverse();
System.out.println("Position: "+dlli.pos);
dlli.add(c);
dlli.traverse();
System.out.println("Position: "+dlli.pos);
dlli.add(a);
dlli.traverse();
System.out.println("Position: "+dlli.pos);
dlli.remove(1);
dlli.traverse();
System.out.println("Position: "+dlli.pos);
dlli.remove(null);
dlli.traverse();
System.out.println("Position: "+dlli.pos);
dlli.clear();
dlli.traverse();
System.out.println("Position: "+dlli.pos);
dlli.add(b);
dlli.traverse();
System.out.println("Position: "+dlli.pos);
dlli.add(a, 0);
dlli.traverse();
System.out.println("Position: "+dlli.pos);
System.out.println("#1: "+dlli.getNth(1));
System.out.println("Position: "+dlli.pos);
System.out.println(dlli.getPredecessor());
System.out.println("Position: "+dlli.pos);
System.out.println(dlli.getPredecessor());
System.out.println("Position: "+dlli.pos);
System.out.println(dlli.getSuccessor());
System.out.println("Position: "+dlli.pos);
System.out.println(dlli.getSuccessor());
System.out.println("Position: "+dlli.pos);
} Monika.

Similar Messages

  • Search LinkedList and display to JtextArea

    The user will type in a first name and hit the "go" button. If the name is in the list it should say the person's name is in the list in the JTextArea, if not it should say the person's name is not in the list in the JTextArea. I have the basic layout, but am lost on how to get what the user typed in the JTextField and the button click and display to textarea to all play together.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class FirstName extends JFrame {
         private static final String names[] = { "Joe", "Mark", "David", "Bryan","Amber","Abigail","Skyler","Melanie" };
         private javax.swing.JButton jButton1;
         private javax.swing.JTextArea jTextArea1;
         private javax.swing.JPanel jPanel1;
         private javax.swing.JTextField jTextField1;
         private java.awt.Label label1;
         public FirstName() {
              initComponents();
              List link = new LinkedList(Arrays.asList(names));     
              setSize( 400, 200 );
              show();
         private void initComponents() {
              jPanel1 = new JPanel();
             label1 = new Label();
              jTextField1 = new javax.swing.JTextField();
              jButton1 = new javax.swing.JButton();
              jTextArea1 = new javax.swing.JTextArea();
              label1.setText("Enter a Name to Search:");
              jPanel1.add(label1);
              jTextField1.setColumns(20);
              jPanel1.add(jTextField1);
              jButton1.setText("Go");
              jButton1.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent evt) {
                        MouseClicked(evt);
              jPanel1.add(jButton1);
              jTextArea1.setColumns(30);
              jTextArea1.setRows(5);
              jPanel1.add(jTextArea1);
              getContentPane().add(jPanel1, BorderLayout.CENTER);
         private void MouseClicked(MouseEvent evt) {
         public static void main(String args[]) {
              FirstName application = new FirstName();
              application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    I'm getting a Syntax error on token "(",";"expected
    for actionPerformed, what is wrong?
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class FirstName extends JFrame {
         private String names[] =
                   "Joe",
                   "Mark",
                   "David",
                   "Bryan",
                   "Amber",
                   "Abigail",
                   "Skyler",
                   "Melanie" };
         private JButton jButton1;
         private JTextArea jTextArea1;
         private JPanel jPanel1;
         private JTextField jTextField1;
         private Label label1;
         public FirstName() {
              initComponents();
              List link = new LinkedList(Arrays.asList(names));
              setSize(400, 200);
              show();
         private void initComponents() {
              jPanel1 = new JPanel();
              label1 = new Label();
              jTextField1 = new javax.swing.JTextField();
              jButton1 = new javax.swing.JButton();
              jTextArea1 = new javax.swing.JTextArea();
              label1.setText("Enter a Name to Search:");
              jPanel1.add(label1);
              jTextField1.setColumns(20);
              jPanel1.add(jTextField1);
              JButton1 = new JButton1("  OK  ");
              jbutton1.addActionListener(new ActionListener(this));
              public void actionPerformed(ActionEvent e) {
                   String entered = jTextField1.getText();
                   // search for "entered" within the list    
                   if (found) {
                        jTextArea1.setText("found");
                   } else {
                        jTextArea1.setText("not found");
                   jPanel1.add(jButton1);
                   jTextArea1.setColumns(30);
                   jTextArea1.setRows(5);
                   jPanel1.add(jTextArea1);
                   getContentPane().add(jPanel1, BorderLayout.CENTER);
         public static void main(String args[]) {
              FirstName application = new FirstName();
              application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

  • Help with JTree's opaque methods

    I have been looking through the methods provided for JTree in Netbeans GUIBuilder and I do not see accessor methods for actions like insertion, retrieval, deletion and replacement. I am looking for something like this.
    JTree.insert('object', JTree.getSelectedNode());
    JTree.getSelectedNode().getObject();
    JTree.deleteNode(JTree.getSelected());
    JTree. supplantObject(‘object’, JTree.getSelectedNode());
    JTree.insert('object', JTree.getSelectedNode()) should accept to inputs; the object you wish to insert and the location you wish to insert it. JTree.getSelectedNode() would be an accessor method returning the selected node. The insert would have to find the next available element in the LinkedList, array, hashtable, stack, (or whatever it uses) and inserts the object.
    JTree.getSelectedNode().getObject(); I assume that if I have “apple” selected in the JTree, “apple” will be returned.
    JTree.deleteNode(JTree.getSelected()); deleting the node wipes out all its children as well.
    JTree. supplantObject(‘object’, JTree.getSelectedNode()); overwrites the object in the selected with a new object.
    These seem like the more obvious accessor methods and I am astonished to find them missing or named something inconsistent with java standards.
    So I guess my question is, what are the equivalent method names for the aforementioned methods?
    BM

    Take a look at [http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/tree/DefaultMutableTreeNode.html|http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/tree/DefaultMutableTreeNode.html] which has most of the methods that you are interested in. A JTree has a single root node, which by default is of this type.

  • Textarea and buttons not displaying

    I've been playing around with the code for awhile. I feel like I'm overlooking something really simple here. But I can't get the app to display the text-box or buttons. Makes it kinda hard to do unit testing. Any advice on oppurtunites would be greatly appreciated!
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class FirstName extends JFrame implements ActionListener {
         private String names[] =
                   "Joe",
                   "Mark",
                   "David",
                   "Bryan",
                   "Amber",
                   "Abigail",
                   "Skyler",
                   "Melanie" };
         private JButton jButton;
         private JTextArea jTextArea;
         private JPanel jPanel;
         private JTextField jTextField;
         private JLabel label;
         public FirstName() {
              initComponents();
              List link = new LinkedList(Arrays.asList(names));
              setSize(400, 200);
              show();
         private void initComponents() {
              jPanel = new JPanel();
              label = new JLabel();
              jTextField = new JTextField();
              jButton = new JButton();
              jTextArea = new JTextArea();
              label.setText("Enter a Name to Search:");
              jPanel.add(label);
              jTextField.setColumns(20);
              jPanel.add(jTextField);
              jButton = new JButton(" OK ");
              jButton.addActionListener(this);
         public void actionPerformed(ActionEvent e) {
              boolean found = true;
              String entered = jTextField.getText();
              if (found) {
                   jTextArea.setText("found");
              } else {
                   jTextArea.setText("not found");
              jPanel.add(jButton);
              jTextArea.setColumns(30);
              jTextArea.setRows(5);
              jPanel.add(jTextArea);
              getContentPane().add(jPanel, BorderLayout.CENTER);
    public static void main(String args[]) {
              FirstName application = new FirstName();
              application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    You've forgotten to add the panel to the frame, eg, at the end of initComponents().
    Have a read of the Swing section in Sun's Tutorial to see an example of the "approved" way of creating and showing the frame. A typical example using invokeLater() is here: [HelloWorldSwing.java|http://java.sun.com/docs/books/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start//HelloWorldSwing.java]. Notice, too, that it uses setVisible(true) rather than the deprecated show().
    (When you post code, use the {code} tags. The idea is that you put {code} at the start of your code and the same thing again at the end. That way your code will be properly formatted and syntax coloured when it appears here.)

  • Java list help

    I am trying to add some thing to my list , its getting added, when I try to add the second item first item is getting overridden, its a reference issue, even I create a new Instance and try to add, but still same issue, can some one please help me
    here is the code I am using
    private Programs theprogram= new Programs();
    public void actionAddProgram(){
         Programs abc= new Programs();
         abc.setProgram(theprogram.getProgram());
         programs.add(abc);
         theprogram= new Programs();
    }

    here is the code
    private int myAddressLineIndex = -1;
         public int getAddressLineIndex() {
              return myAddressLineIndex;
         public void setAddressLineIndex(int theAddressLineIndex) {
              myAddressLineIndex = theAddressLineIndex;
         public void actionAddAddressLine() {
                   if (theprogram.getProgram() == null || theprogram.getProgram().length == 0) {
                        theprogram.setProgram(new String[]{programInstance});
                   }else {
                        List lines = new LinkedList(Arrays.asList(theprogram.getProgram()));
                        if (lines.contains(programInstance)) {
                        }else if (myAddressLineIndex > -1) {
                             lines.remove(myAddressLineIndex);
                             lines.add(myAddressLineIndex, programInstance);
                        }else {
                             lines.add(programInstance);
                        theprogram.setProgram((String[])lines.toArray(new String[lines.size()]));
                   programInstance = "";
                   myAddressLineIndex = -1;
    <TR>
                                                                               <TD><B>Add new Programs:</B></TD>
                                                                               <TD><h:inputText id="text2"
                                                                                    value="#{pc_Organization.programInstance}"
                                                                                    styleClass="inputText" size="60" ></h:inputText></TD>
                                                                               <TD>
                                                                                 <hx:commandExButton value="ADD" title="add another program"
                                                                                  action="#{pc_Organization.actionAddAddressLine}"></hx:commandExButton>
                                                                               </TD>
                                                                          </TR>
                                                                          <TR>
                                                                          <TD>
                                                                          </TD>
                                                                          <TD>
                                                                          <hx:dataIterator value="#{pc_Organization.theprogram.program}" var="pro">
                                                                              <h:outputText value="#{pro}"/>
                                                                          </hx:dataIterator>
                                                                          </TD>
                                                                          </TR>
    public class Programs {
         private String[] program;
         public String[] getProgram() {
              return program;
         public void setProgram(String[] program) {
              this.program = program;
    }I have all the code here, can some one help now???

  • Array of linkedlist of object - help! plesse!

    I am writing an array of linkedlist and the elements of the linkedlist is an object carrying 2 interger. It didn't compile and the message is as follows:
    C:\thesis5>javac testLL2.java
    testLL2.java:22: cannot resolve symbol
    symbol : variable vertexFanObj2
    location: class testLL2
    vertexFanObj2 = myLL2[ i].get(j);
    ^
    1 error
    My program is as follows:
    import java.net.*;
    import java.io.*;
    import java.util.LinkedList;
    public class testLL2 {
    public static void main(String[] args) throws IOException {
    int myLLLength;
    Integer intObj;
    LinkedList myLL2 [] = new LinkedList[10];
    vertexFan vertexFanObj;
    for (int i = 0; i < 10; i++) {
    myLL2[ i] = new LinkedList();
    for (int j=0; j < 5; j++) {
    vertexFanObj = new vertexFan();
              vertexFanObj.setupVertex(j, -j);
    myLL2.add(vertexFanObj);
    for (int i = 0; i < 10; i++) {
    myLLLength = myLL2[ i].size();
    for (int j=0; j<myLLLength; j++) {
    vertexFanObj2 = myLL2[ i].get(j);
    System.out.println(vertexFanObj.vertex1+" "+vertexFanObj.vertex2);
    class vertexFan {
    int vertex1, vertex2;
    void setupVertex(int vertexA, int vertexB) {
    vertex1=vertexA;
    vertex2=vertexB;
    I 've got lost! Please kindly help you! Many thanks in advance!

    for (int i = 0; i < 10; i++) {
    myLL2[ i] = new LinkedList();
    for (int j=0; j < 5; j++) {
    vertexFanObj = new vertexFan();
    vertexFanObj.setupVertex(j, -j);
    myLL2.add(vertexFanObj);
    for (int i = 0; i < 10; i++) {
    myLLLength = myLL2[ i].size();
    for (int j=0; j<myLLLength; j++) {
    vertexFanObj2 = myLL2[ i].get(j);
    System.out.println(vertexFanObj.vertex1+" "+vertexFanObj.vertex2);
    } Its a scope issue.
    You define vertexFanObj in a for loop. then try to access it from outside that for loop. (in another for loop)
    for (int i = 0; i < 10; i++) {
    myLL2[ i] = new LinkedList();
    vertexFanObj = new vertexFan(); //I MOVED THIS LINE
    for (int j=0; j < 5; j++) {
    vertexFanObj.setupVertex(j, -j);
    myLL2.add(vertexFanObj);
    for (int i = 0; i < 10; i++) {
    myLLLength = myLL2[ i].size();
    for (int j=0; j<myLLLength; j++) {
    vertexFanObj2 = myLL2[ i].get(j);
    System.out.println(vertexFanObj.vertex1+" "+vertexFanObj.vertex2);
    } should work properly...

  • Converting a linkedlist to an array

    I currently have a program which reads in values from a file and stores them in a linked list, but i would like to convert this linked list to an array so i can use my bubble sort code on it which ive already got and it works by sorting through an array. i've tried using the .toArray() method on the list to convert it to an array but its not working. can anyone help me out here?

    try something like this:
    LinkedList list = new LinkedList();
    ... // populating the list
    Object[] listItems = (Object[])list.toArray(new Object[0]);you should replace Object[] by the Class type you are going to resolve (String[], Integer[], SomethingElse[], ...).

  • A suggestion : use "loop array list" instead of ArrayList / LinkedList

    ArrayList is good at:
    get / set by index : O(1)
    appending : O(log(n))
    remove last : O(1)
    and very bad at:
    add middle : O(n)
    remove from middle : O(n)
    LinkedList is good at:
    fast remove from middle, if your iteraror already goes there : O(1)
    convenient methods : addFirst, addLast, removeFirst, removeLast : O(1)
    and very bad at :
    get / set by index : O(n)
    here I want to make a suggestion : use "loop array list" instead of the ArrayList and LinkedList.
    a "loop array list" is based on array, just like ArrayList. But it has 2 member-variables : the start position, and the real size. the start position can be anywhere within array.length. an element of index "i" is stored in array[ start + i ], and when (start + i > array.length), loop to the beginning of the array; when (start + i < 0), loop to the end of the array.
    this "loop array list" has all the good sides:
    get / set by index : O(1)
    add first / last : O(log(n))
    remove first / last : O(log(n))
    add / remove from middle : O(n)
    (note : because we shrink the backup-array when the real size is too small, add / remove operation take O(log(n)) now.)
    the only problem is : add / remove from middle. let's take a look at it.
    1. the LinkedList does NOT really add/remove from middle in O(1), you has to locate the element, which is O(n).
    2. O(n) is acceptable, O(n^2) is not acceptable. try this : keep removing first element from an very big ArrayList ( size>10^6 ) until it's empty.
    the fact is, any list can perform batch-remove / batch-add operation in O(n) instead of O(n^2). it's easy : allocate a new list, iterate the original list, copy the element into the new list if condition is satisfied.
    so, instead of "remove from middle", what we need is a new methods : removeAllByCondition( Condition condition ), and now the batch-remove operation can be done in O(n)
    here is an implementation of mine. I've tested it on my computer( 512mem + 2G cpu, win2k + jdk1.5 ), it's amazing, just a little slower then ArrayList when add last, and a liitle slower then LinkedList when batch-remove. in all other cases, it's far more better then those 2 kinds of List.
    // source code : List2
    import java.util.AbstractList;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.NoSuchElementException;
    import java.util.Set;
    public final class List2<T> extends AbstractList<T> {
    private static int initialArrayLength = 4;
    private T[] array;
    private int start;
    private int size;
    private void init( T[] newArray, int start_a, int size_a ) {
    array = newArray;
    start = start_a;
    size = size_a;
    @SuppressWarnings("unchecked")
    private void init() {
    init( (T[]) new Object[ initialArrayLength ], 0, 0 );
    public List2() {
         init();
    @SuppressWarnings("unchecked")
    public List2( Collection<? extends T> collection ) {
         init(
              collection.toArray( (T[]) new Object[ collection.size() * 11 / 10 + 1 ] ),
              0,
              collection.size()
    private List2( T[] array_a, int start_a, int size_a ) {
         init( array_a, start_a, size_a );
    @SuppressWarnings("unchecked")
    public static <TT> List2<TT> createV( TT... elements ) {
         TT[] array = (TT[]) new Object[ elements.length * 11 / 10 + 1 ];
         System.arraycopy( elements, 0, array, 0, elements.length );
         return new List2<TT>( array, 0, elements.length );
    public static List2<Double> create( double... elements ) {
         Double[] array = new Double[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array[i] = elements;
         return new List2<Double>( array, 0, elements.length );
    public static List2<Integer> create( int... elements ) {
         Integer[] array2 = new Integer[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array2[i] = elements[i];
         return new List2<Integer>( array2, 0, elements.length );
    public static List2<Character> create( char... elements ) {
         Character[] array2 = new Character[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array2[i] = elements[i];
         return new List2<Character>( array2, 0, elements.length );
    public static List2<Character> create( String s ) {
         return create( s.toCharArray() );
    public List2<T> clone() {
         return new List2<T>( this );
    // basic
    public int size() {
         return size;
    private int index( int index ) {
         int i = start + index;
         if( i >= array.length )
              i -= array.length;
         return i;
    public T get( int d ) {
         if( d < 0 || d >= size )
              throw new IndexOutOfBoundsException();
         if( size == 0 )
              throw new NoSuchElementException();
         return array[ index( d ) ];
    public T set( int index, T element ) {
         if( index < 0 || index >= size )
              throw new IndexOutOfBoundsException();
         int i = index( index );
         T oldElement = array[i];
         array[i] = element;
         return oldElement;
    @SuppressWarnings("unchecked")
    private void copyAndSetToNewArray( int newArrayLength ) {
         T[] newArray = (T[]) new Object[ newArrayLength ];
         for( int i=0; i<size; i++ )
              newArray[i] = array[ index( i ) ];
         init( newArray, 0, size );
    public void addFirst( T element ) {
         if( size == array.length )
              copyAndSetToNewArray( size * 3 / 2 + 1 );
         int i = index( array.length - 1 );
         array[ i ] = element;
         start = i;
         size++;
    public void addLast( T element ) {
         if( size == array.length )
              copyAndSetToNewArray( size * 3 / 2 + 1 );
         array[ index( size ) ] = element;
         size++;
    public T removeFirst() {
         if( size == 0 )
              throw new NoSuchElementException();
         T oldElement = array[ start ];
         array[ start ] = null;
         start = index( 1 );
         size--;
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return oldElement;
    public T removeLast() {
         if( size == 0 )
              throw new NoSuchElementException();
         int i = index( size - 1 );
         T oldElement = array[i];
         array[i] = null;
         size--;
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return oldElement;
    @SuppressWarnings("unchecked")
    public int removeAll( ListCondition<T> condition ) {
         T[] newArray = (T[]) new Object[ array.length ];
         int iNew = 0;
         for( int i=0; i < size; i++ ) {
              T element = get( i );
              if( ! condition.isConditionSatisfied( this, i, element ) )
                   newArray[ iNew++ ] = element;
         int oldSize = size;
         init( newArray, 0, iNew );
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return size - oldSize;
    // aux
    public boolean equals(Object obj) {
         if( obj == this )
         return true;
         if( obj instanceof List2 ) {
              List2 that = (List2) obj;
              if( this.size != that.size )
                   return false;
              for( int i=0; i < size; i++ )
                   if( ! Tools.equals( this.array[ this.index(i) ], that.array[ that.index(i) ] ) )
                        return false;
              return true;
         if( obj instanceof List ) {
              List that = (List) obj;
              if( this.size != that.size() )
                   return false;
              Iterator thatIter = that.iterator();
              for( int i=0; i < size; i++ )
                   if( ! Tools.equals( this.array[ this.index(i) ], thatIter.next() ) )
                        return false;
              return true;
         return true;
    public int hashCode() {
         int hashCode = 1;
         for( int i=0; i < size; i++ ) {
              T element = array[ index( i ) ];
         hashCode = 31*hashCode + ( element==null ? 0 : element.hashCode() );
         return hashCode;
    public boolean isEmpty() {
         return size == 0;
    public T getFirst() {
         return get( 0 );
    public T getLast() {
         return get( size() - 1 );
    public T getRandom() {
         return get( (int) (Math.random() * size) );
    public int indexOf( Object element ) {
         for( int i=0; i < size; i++ )
              if( Tools.equals( array[ index( i ) ], element ) )
                   return i;
         return -1;
    public int lastIndexOf( Object element ) {
         for( int i=size-1; i >= 0; i-- )
              if( Tools.equals( array[ index( i ) ], element ) )
                   return i;
         return -1;
    public boolean contains( Object element ) {
         return indexOf( element ) != -1;
    public boolean add( T element ) {
         addLast( element );
         return true;
    @Deprecated
    public void add( int index, T element ) {
         throw new UnsupportedOperationException();
    public T remove() {
         return removeFirst();
    @Deprecated
    public boolean remove( Object element ) {
         throw new UnsupportedOperationException( "use removeAll( Condition ) instead" );
    @Deprecated
    public T remove( int index ) {
         throw new UnsupportedOperationException( "use removeAll( Condition ) instead" );
    public void clear() {
         init();
    public Object[] toArray() {
         Object[] result = new Object[ size ];
         for( int i=0; i < size; i++ )
         result[i] = array[ index( i ) ];
         return result;
    @SuppressWarnings("unchecked")
    public <TT> TT[] toArray( TT[] a ) {
    if( a.length < size )
    a = (TT[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size );
    for( int i=0; i < size; i++ )
    a[i] = (TT) array[ index( i ) ];
    if( a.length > size )
         a[size] = null;
    return a;
    @SuppressWarnings("unchecked")
    public void sort() {
         Object[] a = toArray();
         Arrays.sort( a );
         for( int i=0; i < size; i++ )
              array[ i ] = (T) a[ i ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sortDesc() {
         Object[] a = toArray();
         Arrays.sort( a );
         for( int i=0, j=size-1; i < size; i++, j-- )
              array[ i ] = (T) a[ j ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sort( Comparator<T> comparator ) {
         T[] a = (T[]) toArray();
         Arrays.sort( a, comparator );
         for( int i=0; i < size; i++ )
              array[ i ] = a[ i ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sortDesc( Comparator<T> comparator ) {
         T[] a = (T[]) toArray();
         Arrays.sort( a, comparator );
         for( int i=0, j=size-1; i < size; i++, j-- )
              array[ i ] = a[ j ];
         start = 0;
    public String toString( String delimiter ) {
         return toString( "", delimiter, "", size() );
    public String toString( String prefix, String delimiter, String suffix, int max ) {
         StringBuffer stringBuffer = new StringBuffer( prefix );
         int dest = Math.min( max, size );
         for( int i=0; i < dest; i++ ) {
              stringBuffer.append( get(i) );
              if( i < dest - 1 )
                   stringBuffer.append( delimiter );
         if( size > max )
              stringBuffer.append( "...(" ).append( size() - max ).append( " more)" );
         stringBuffer.append( suffix );
         return stringBuffer.toString();
    // batch operation
    public boolean containsAll( Collection<?> that ) {
         Set<Object> thisSet = new HashSet<Object>( this );
         for( Object element : that )
              if( ! thisSet.contains( element ) )
                   return false;
         return true;
    @SuppressWarnings("unchecked")
    public List2<T> subList( int fromIndex, int toIndex ) {
         if( fromIndex < 0 || toIndex > size || toIndex < fromIndex )
              throw new IndexOutOfBoundsException();
         int newSize = toIndex - fromIndex;
         T[] newArray = (T[]) new Object[ newSize * 11 / 10 + 1 ];
         for( int i=fromIndex, iNew=0; i < toIndex; i++, iNew++ )
              newArray[ iNew ] = array[ index( i ) ];
         return new List2<T>( newArray, 0, newSize );
    public void addV( T... that ) {
         for( T element : that )
              addLast( element );
    public boolean addAll( Collection<? extends T> that ) {
         for( T element : that )
              addLast( element );
         return ! that.isEmpty();
    @Deprecated
    public boolean addAll( int index, Collection<? extends T> c ) {
         throw new UnsupportedOperationException();
    public void removeRest( T element ) {
         int position = lastIndexOf( element );
         if( position == -1 )
              return;
         while( ! Tools.equals( element, removeLast() ) );
    public void removeAllEquals( final T element ) {
         removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T currentElement) {
              return currentElement.equals( element );
    public void removeAllBetween( final T from, final T to ) {
         removeAll( new ListCondition<T>() {
              @SuppressWarnings("unchecked")
              public boolean isConditionSatisfied(List2 list, int index, T element) {
                   if( from != null && ((Comparable) from).compareTo( element ) > 0 )
                        return false;
                   if( to != null && ((Comparable) to).compareTo( element ) <= 0 )
                        return false;
                   return true;
    public boolean retainAll( Collection<?> that ) {
         final Set<Object> thatSet = new HashSet<Object>( that );
         int removeCount = removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T element) {
              return ! thatSet.contains( element );
         return removeCount > 0;
    public boolean removeAll( Collection<?> that ) {
         final Set<Object> thatSet = new HashSet<Object>( that );
         int removeCount = removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T element) {
              return thatSet.contains( element );
         return removeCount > 0;
    // unit test
    private static int maxTestCount = 1000 * 1000;
    public static void unitTest() throws Exception {
         // thest thoese methods for one time
         Tools.ensureEquals( new List2(), new ArrayList() );
         Tools.ensureNotEquals( List2.create( "abcde" ), new ArrayList() );
         Tools.ensureNotEquals( List2.create( "abcde" ), List2.create( "abcdef" ) );
         final List<Double> list1 = new ArrayList<Double>();
         final List2<Double> list2 = new List2<Double>();
         Runnable[] tasks = new Runnable[] {
              // test those methods that do NOT change the list
              new Runnable() { public void run() {
                   Tools.ensureEquals( new List2<Double>( list1 ), list1 );
                   Tools.ensureEquals( List2.createV( list1.toArray() ), list1 );
                   Tools.ensureEquals( List2.createV( list1.toArray( new Double[0] ) ), list1 );
                   double[] doubles = new double[ list1.size() ];
                   int i = 0;
                   for( double d : list1 )
                        doubles[i++] = d;
                   Tools.ensureEquals( List2.create( doubles ), list1 );
                   Tools.ensure( list1.isEmpty() == list2.isEmpty() );
                   Arrays.equals( list1.toArray(), list2.toArray() );
                   Tools.ensureEquals( list1, list2.clone() );
                   Double notExistElement = -2.0;
                   Tools.ensure( list1.indexOf( notExistElement ) == -1 );
                   Tools.ensure( list1.lastIndexOf( notExistElement ) == -1 );
                   Tools.ensure( list1.contains( notExistElement ) == false );
                   Tools.ensureEquals( list1.toString(), list2.toString() );
                   Tools.ensureEquals( list1.toString(), list2.toString() );
                   Tools.ensureEquals( list1.hashCode(), list2.hashCode() );
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.get(0).equals( list2.getFirst() ) );
                   Tools.ensure( list1.get(list1.size()-1).equals( list2.getLast() ) );
                   Double existRandomElement = list2.getRandom();
                   Tools.ensure( list1.contains( existRandomElement ) );
                   Tools.ensure( list2.contains( existRandomElement ) );
                   Tools.ensure( list1.indexOf( existRandomElement ) == list2.indexOf( existRandomElement ) );
                   Tools.ensure( list1.indexOf( existRandomElement ) == list2.indexOf( existRandomElement ) );
                   int from = (int) (Math.random() * list1.size());
                   int to = (int) (Math.random() * (list1.size()+1));
                   if( from > to ) {
                        int t = from;
                        from = to;
                        to = t;
                   Tools.ensureEquals( list1.subList( from, to ), list2.subList( from, to ) );
              // test those methods that change the list
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = (int) (Math.random() * list1.size());
                   double d = Math.random();
                   list1.set( i, d );
                   list2.set( i, d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = (int) (Math.random() * list1.size());
                   Tools.ensure( list1.get( i ).equals( list2.get( i ) ) );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( 0, d );
                   list2.addFirst( d );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.addLast( d );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.addLast( d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove( 0 ).equals( list2.removeFirst() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove( list1.size() - 1 ).equals( list2.removeLast() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = 0;
                   for( Iterator<Double> iter=list1.iterator(); iter.hasNext(); i++ ) {
                        iter.next();
                        if( i % 3 == 0 )
                             iter.remove();
                   list2.removeAll( new ListCondition<Double>() { public boolean isConditionSatisfied(List2 list, int index, Double element) {
                        return index % 3 == 0;
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.add( d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove(0).equals( list2.remove() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int r = (int) (Math.random() * list1.size());
                   Double element = list1.get( r );
                   int index = list1.lastIndexOf( element );
                   for( int i=list1.size()-1; i>=index; i-- )
                        list1.remove( i );
                   list2.removeRest( element );
              new Runnable() { public void run() {
                   list2.removeRest( Math.random() - 2 );
              new Runnable() { public void run() {
                   list1.clear();
                   list2.clear();
              new Runnable() { public void run() {
                   Collections.sort( list1 );
                   list2.sort();
              new Runnable() { public void run() {
                   Collections.sort( list1 );
                   Collections.reverse( list1 );
                   list2.sortDesc();
              new Runnable() { public void run() {
                   Comparator<Double> comparator = new Comparator<Double>() { public int compare(Double o1, Double o2) {
                        return o1.toString().substring(2).compareTo( o2.toString().substring(2) );
                   Collections.sort( list1, comparator );
                   list2.sort( comparator );
              new Runnable() { public void run() {
                   Comparator<Double> comparator = new Comparator<Double>() { public int compare(Double o1, Double o2) {
                        return o1.toString().substring(2).compareTo( o2.toString().substring(2) );
                   Collections.sort( list1, comparator );
                   Collections.reverse( list1 );
                   list2.sortDesc( comparator );
              new Runnable() { public void run() {
                   Double notExistElement = -2.0;
                   list2.removeAllEquals( notExistElement );
                   Tools.ensureEquals( list1, list2 );
                   list2.removeAllBetween( 0.5, 0.6 );
                   for( Iterator<Double> iter=list1.iterator(); iter.hasNext(); ) {
                        double d = iter.next();
                        if( d >= 0.5 && d < 0.6 )
                             iter.remove();
                   Tools.ensureEquals( list1, list2 );
         System.out.print( "test List2 " );
         for( int i=0; i < maxTestCount; i++ ) {
              tasks[ (int) (Math.random() * tasks.length) ].run();
              Tools.ensureEquals( list1, list2 );
              if( i % (maxTestCount/10) == 0 )
                   System.out.print( "." );
         System.out.println( " ok" );
    // source code : ListCondition
    public interface ListCondition<T> {
    boolean isConditionSatisfied( List2 list, int index, T element );

    Hi,
    I have the following statement:
    private List list = new ArrayList();
    why not use private ArrayList list = new
    ArrayList()?
    I know ArrayList implements List, so list has a wide
    scope, right? What's the benefit?
    Thanks,
    JieBy using the interface you are not tied to a specific implementation.
    Later, you may determine that using a LinkedList is more efficient to your specific code and then all you need to do is change the statement to:
    private List list = new LinkedList();As long as you are not casting the list reference to ArrayList (or something along those lines) you would not need to change anything else.

  • Switching between LinkedList and Array

    Hi, I'm new to OOP and Java so please bear with me.
    I've been given an assignment to code my own collection
    similar to the Java Collection. It has to have sorted arrays,
    unsorted arrays, sorted linked lists and unsorted linked lists.
    Basically, the user has to be able to switch between an
    array and a linked list if desired.
    I have a variable that should only be set once and stays
    constant even tho the user may switch between an array
    and a linked list. So, say
    constant variable x
    List myList = new Array();
    myList.set(x) = 10;
    myList = new LinkedList();
    In my current implementation, I am losing the value of x
    after I switch to a linked list. The value of x is then null.
    My question is how do I set up my hierarchy so that I can
    get the value of x when I switch to a linked list?
    Any help appreciated
    Edited by: sabatier_sabrika on Oct 28, 2008 9:32 AM

    sabatier_sabrika wrote:
    I have a variable that should only be set once and stays
    constant even tho the user may switch between an array
    and a linked list. So, say
    constant variable x
    List myList = new Array();
    myList.set(x) = 10;
    myList = new LinkedList();I assume that this is pseudo-code, as it definitely doesn't compile.
    >
    In my current implementation, I am losing the value of x
    after I switch to a linked list. The value of x is then null.
    My question is how do I set up my hierarchy so that I can
    get the value of x when I switch to a linked list?That's a rather curious requirement.
    There's no way for the new LinkedList object to know of the content in the Array object in your example.
    You can however provide a constructor for your classes that takes a List and initializes its content with that List:
    List myList = new Array();
    myList.add(x);
    myList = new LinkedList(myList);This way the new LinkedList contains the content of the Array.

  • How do I get an array of LinkedLists?

    I need an array of liked lists
    I tryed the code:
    LinkedList buckets[] = new LinkedList[radix];But that generated an unchecked warning when I tried to put an Integer into it.
    I changed it to:
    LinkedList<Integer> buckets[] = new LinkedList<Integer>[radix];But that generated a "generic array creation" error.
    is it possible to to get an array of lists without warnings?

    It is possible to use generic arrays (simple ones)
    e.g.
    import java.util.List;
    public class Test
       public static void main(String[] args)
          String[] elements = new String[]{"Happy","Go","Lucky"};
          String middleElement = middleElement(elements);
          System.out.println(middleElement);
       public static <T> T middleElement(T[] elements)
          return elements[elements.length/2];
    }However you cannot (should not) create generic arrays with bounded parameters.
    Lets say that we have somehow create a generic array:
    List<String>[] lists = ...
    Then since lists is an array we can assign it to Object[]
    Object[] objArray = lists;
    and now we can put any list in the array.
    objArray[0] = new ArrayList<Rectangle>();
    Even though this should not happen, the runtime has no way to check aginst it and so no ArrayStoreException is thrown.
    You are however free to:
    List<?>[] lists = new List<?>[5];
    which implies its an array of any type of List.

  • NullPointerException with an array of LinkedList

    Hello Everybody.
    I'm new to Java and I am trying to use a quite complicated data structure but I am missing something since it does not work.
    Here comes my code:
    import java.util.LinkedList;
    class ObjectToHold {
    public int i;
    ObjectToHold (int j) {
    i=j;
    public class ModifiedArray {
    static final int ARRAY_DIMENSION = 79;
    private LinkedList[] myInternalArray;
    ModifiedArray() {
    LinkedList[] myInternalArray = new LinkedList[ARRAY_DIMENSION];
    for (int i=0;i<ARRAY_DIMENSION;i++) {
    myInternalArray[i] = new LinkedList();
    void insert (int slot, ObjectToHold a) {
    ((LinkedList)myInternalArray[slot]).addLast(a);
    public static void main(String[] args) {
    ModifiedArray myModifiedArray = new ModifiedArray();
    for (int j=0; j<ARRAY_DIMENSION;j++) {
    myModifiedArray.insert(j,new ObjectToHold(j));
    The class ModifiedArray contains a private array of LinkedList objects. I wrote an "insert" method to put objects of type ObjectToHold (which is a very simple one!) into the array.
    While compiling the code, everything works fine.
    On the other hand, when I run the compiled code I get the following run time Exception:
    Java.lang.NullPointerException
    at ModifiedArray.insert ....
    Modified.Array.main ...
    The problem must be in the way I use the reference to myInternalArray.
    I also tried
    myInternalArray[slot].addLast(a);
    instead of
    ((LinkedList)myInternalArray[slot]).addLast(a);
    but I got the same result.
    Can anybody help me or do I have to ask in some other forum?
    Thank you very much
    Tommaso

    You defined myInternalArray as local to the constructor as well as an instance variable.
    Try..
    import java.util.LinkedList;
    class ObjectToHold {
      public int i;
      ObjectToHold (int j) {
        i=j;
    public class ModifiedArray {
      static final int ARRAY_DIMENSION = 79;
      private LinkedList[] myInternalArray;
      ModifiedArray() {
        myInternalArray = new LinkedList[ARRAY_DIMENSION];
        for (int j=0; j<ARRAY_DIMENSION; j++) {
          myInternalArray[j] = new LinkedList();
      void insert (int slot, ObjectToHold a) {
        ((LinkedList)myInternalArray[slot]).addLast(a);
      public static void main(String[] args) {
        ModifiedArray myModifiedArray = new ModifiedArray();
        for (int j=0; j<ARRAY_DIMENSION;j++) {
          myModifiedArray.insert(j,new ObjectToHold(j));
    }

  • LinkedList to array

    Hi, I just started working with linkedlists and I have some questions
    I'm trying to store the contents of a LinkedList in an array. Everything in the list is of the type Compeditor, a class I have written. I have tried this:
    Object[] objArray = Maraton.toArray(Object[]);
    Compeditor[] coArray = (Compeditor) objArray;(Maraton is the name of my LinkedList)
    But it doesn't work.. Any ideas?
    In addition to this I would like to ask if anyone knows an easy way to BubbleSort a LinkedList based on one of the Strings in my Compeditor class.
    Edited by: YZF-R1 on May 10, 2008 11:29 AM

    morgalr wrote:
    Someplace you defined your LinkedList, it's a generic so you probably supplied an Object type:
    LinkedList<myObject> ll = new LinkedList<myObject>();
    //more of your code here
    //So eventually you get to this point:
    myObject[] o = ll.toArray(new myObject[0]);Though I have not had occasion to use this, it is the example almost direct from the API documentation. It's a wonderful document, you should check it out.That worked, thanks alot =)

  • Vectors VS Arrays VS LinkedLists

    Hi
    I am basically looking for some info on the advantages or disadvantages of using any of the above. I would like to know how one justifies the use of one over the other.
    I would be grateful for any pointers or resources you could point me to.
    Cheers

    Use arrays if you know the size you will need, you won't be inserting or removing elements and you need highly efficient indexed access to the elements.
    Use ArrayList if you don't know how large to make the container, you need efficient indexed access to the elements, you don't need to have efficient insertion or removal of elements from the interior of the container and you don't need thread safety on the individual operations (the most common case).
    Use Vector or a synchronized ArrayList is your needs are like those for ArrayList but you need thread safety of the individual operations.
    Use LinkedList if you don't need efficient indexed access but you do need efficient insertion and removal of elements from the interior of the container and you don't need thread safety of individual operations (the usual case).
    Use the synchronized wrapper of LinkedList if your needs are like those that lead you to LinkedList but you need thread safe individual operations.
    I am sure this is documented better someplace else, but I haven't taken the time to check.
    Chuck

  • Question concerning LinkedList of int arrays

    This is probably a stupid question, but...
    The following section of code is intended to examine the vertices of a graph, set the value of nMatrix[j][k] to 0 whenever there is no edge connecting vertices j and k, and place an int array {j,k} into a LinkedList setN whenever an edge does connect vertices j and k.
           /*g is the graph, getV() returns the array of vertices*/
    int[][] nMatrix = new int[g.getV().length][g.getV().length];
            /*set N*/ LinkedList setN = new LinkedList();
            for (int j = 0; j < g.getV().length; j++) {
                for (int k = 0; k < g.getV().length; k++) {
                    if (g.getV()[j].hasNeighbor(g.getV()[k]))
                        /*place the n_jk in set N*/
                        setN.add(new int[] {j,k});
                    else nMatrix[j][k] = 0;
            }The code does what it's supposed to do as far as I can tell, but my question is: How do I retrieve the arrays in setN as int[]'s rather than instances of the Object class? For a moment I thought I could use
    Integer[] n = (Integer[])setN.get(index);to retrieve the array, but that returned a run-time error. Can anyone out there provide some input?

    I can now retrieve arrays from my LinkedList without any problems, but when I try to find an array within that LinkedList using the indexOf() method, it always returns -1.
    My code:
    static boolean solvable (Graph g) {
            Vertex[] v = g.getV();
            int[] c = g.getC();
            int[] d = g.getD();
            int c_sum = sum(c);
            int d_sum = sum(d);
            /* snip */
            LinkedList setN = new LinkedList();
            //here's where I add arrays to set N
            for (int h = 0; h < v.length; h++) {
                for (int j = 0; j < v.length; j++) {
                    if (v[h].hasNeighbor(v[j])) {
                        setN.add(new int[] {h,j});
    /*each array of size 2 in setN corresponds to a certain int value; this array contains those values*/
            int[] setN_vals = new int[setN.size()];
            for (int j = 0; j < setN_vals.length; j++) {
                setN_vals[j] = 0;
            /*snip*/
    //This next function takes the LinkedList setN as an argument.  It is called within the body of solvable().
    static boolean Watsons(int k, int m, LinkedList setN,  int[] vals, int cmd) {
            int total = 0;
            for (int l = 0; l < m; l++) {
                int n_index = setN.indexOf(/*(Object)*/new int[] {k,l});  /*this always returns -1, even if the array {k,l} had earlier been placed in setN*/
                if (n_index > -1)
                    total += 2 * vals[n_index];
            /* snip */
        }I've tried it with and without the (Object) coercion tag, but it doesn't seem to be able to find the array either way.

  • How do I create an array of LinkedList

    can anyone help me??

    You can't use generics syntax for that. It is a limitation of java's generics.
    Just do
    private LinkedList<Integer>[] linkedListArray = (LinkedList<Integer>[])new LinkedList[10];
    see http://www.informatics.susx.ac.uk/courses/dats/notes/html/node181.html
    Edited by: dmbdmb on Feb 20, 2008 12:12 AM

Maybe you are looking for

  • Jumps issue

    Hi All, I having an issue in one of my reports. I am sure whether its an issue with jumps or particular variable. Well here's the issue: In the sender report( weekly report) I have "net gallons" being displyed for  4 weeks(week1, week2, week3, week4)

  • Lost all info on handheld.

    The battery ran out on my Tungsten E2 and much, but not all, data was lost for some bizarre reason.  I use a mac at home and a pc a work.  I would normally just sync with my up-to-date work computer, but I lost my job and have no access.  I do, howev

  • HT201263 I restored my ipod but it continues to ask for a screen lock password what can i do next?

    ive tried to restore it in two modes.. from my laptop by clicking restore and in recovery mode. any suggestions??

  • Where can i download database server 8.1.5?

    Where can i download database server 8.1.5? All download links to 8.x looks dead.

  • Cin Issue for capital

    Hello Together, Could you pl.share me the following, Excise accounts per excise transaction for CAPE IP ( Debit / credit entry) GL accounts per excise transaction for CAPE IP Thank you in advance Shailesh