Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop with a generic array?

Tags:

java

adt

Going back over my basic ADT stuff here, and trying to kill two birds with one stone by learning Java while I amTrying to write a simple algorithm for a merge sort with a generic linked list ( which I am creating myself). It's proving to be far more difficult than I had first imagined ! Can anyone help me out please ? I will start out working on the basics and will update this post as I get further in.

My code for the generic linked list is as follows :

    public class NodeList<T> {
  private Comparable head;
  private NodeList tail;
  public NodeList( Comparable item, NodeList list ) {
    head = item;
    tail = list;
  }

}

I am trying to access this class in another class I have made, which is as follows :

public class MyList<T> {

  private NodeList<T> nodes;
  private int size;
  public MyList( ) { 
    nodes = null; 
  }

  public MyList(T[] array ){
    for(int countArray = 0; countArray <= array.length() ; countArray++) {
      nodes= new NodeList( value, nodes );
      size++;
    }
  }

which should add generic items from an array, using a linked list. Unfortunately, it doesn't and this is the first problem I have encountered. I am getting the error :

cannot find symbol : method length().

Can someone give me some advice on how I could fix this?

Many thanks!

like image 537
Stephen Quinn Avatar asked Sep 09 '26 02:09

Stephen Quinn


1 Answers

on the array you don't have a length() method but a length member : array.length

Additionally, you'll want to stop iterating before countArray reaches array.length and initialise size before using it:

final int arrayLength = array.length;
size = arrayLength;
nodes = null;
for(int i = 0; i < arrayLength; ++i) {
      nodes = new NodeList(array[i], nodes);
}

or

nodes = null;
size = array.length;
for(T element : array) {
      nodes = new NodeList(element, nodes);
}
like image 139
Vincent Mimoun-Prat Avatar answered Sep 10 '26 15:09

Vincent Mimoun-Prat