简体   繁体   中英

Can not find symbol - method error

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM