1

I'm struggling a little with learning generic classes and implementation.

I'm trying to create a generic class that extends ArrayList (I'm aware this is bad practice, it's just something I have to do). I want to use a comparable to sort the entries in to the arrayList (I'm not allowed to use .sort(). Here is the extended class:

import java.util.ArrayList;
import java.util.*;

/**
 * extending to ArrayList
 */
public class SortedArrayList<E> extends ArrayList<E> 
{

/**
 * Constructing the super
 */
public SortedArrayList()    
{
   super();

  }

  public  void insertAndSort (E element){
  if (isEmpty()){
      add(element);
    }

  for ( int i = 0; i < size(); i++){
      E otherElement = get(i);
      if(element.compareTo(otherElement) > 0){
          add(i, element);
        }
      if(element.compareTo(otherElement) < 0) {
          add(i+1, element);
        }
    }

}

}

I want to implement the compareTo method in the class of the objects being sorted, but when I try to compile the SortedArrayList class it's returning an error saying "can not recognise symbol - method compareTo(E)". I know that that's because "element" isn't actually an object to call on, it's meant to be generic. Is there a way to tell the compiler that the compareTo() method is being called from an object that doesn't exist right now, but will when it's called?

Am_I_Helpful
  • 17,636
  • 7
  • 44
  • 68
Finlay
  • 31
  • 9

1 Answers1

5

You should declare the class like this:

public class SortedArrayList<E extends Comparable> extends ArrayList<E>

compareTo() is available only to classes which implements Comparable

Stav Saad
  • 589
  • 4
  • 13