Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Generics problem

  1. #1
    Junior Member
    Join Date
    Feb 2011
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Unhappy Generics problem

    Im having a problem with my generic class for a ordered set. It will compile when I don't have the beginning of the class with <E extends Comparable<E>. When I have this (which i need to be able to compare two objects) it will give me the error :
    Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
    at GenOrderedSet.<init>(GenOrderedSet.java:11)
    at tester.main(tester.java:11)

    This is my class:

    public class GenOrderedSet<E extends Comparable<E>> implements Cloneable
    {
     
       private E[ ] data;
       private int manyItems; 
     
       public GenOrderedSet( )
       {
          final int INITIAL_CAPACITY = 10;
          manyItems = 0;
          data = (E[]) new Object[INITIAL_CAPACITY];
       }
     
     
     
       public GenOrderedSet(int initialCapacity)
       {
          if (initialCapacity < 0)
             throw new IllegalArgumentException
             ("The initialCapacity is negative: " + initialCapacity);
          data = (E[]) new Object[initialCapacity];
          manyItems = 0;
       }
     
     
       public void add(E element)
       {
    	   if (manyItems == data.length){
    	        ensureCapacity(manyItems*2+1);
    	    }
    	    int location = 0;
    	    while(location < manyItems && element.compareTo(data[location]) > 0) {
    	    	location++;
    	    }
    	    for(int i = manyItems-1; i>=location; i--){
    	    	if(element == data[location]){
    	    		throw new IllegalArgumentException("Can't have duplicates");
    	    	}
    	    	else{
    	    	data[i+1] = data[i];
    	    	data[location] = element;
    	    	manyItems++;
    	    	}
    	    }
       }
     
     
         public void addMany(E... elements)
       {
          if (manyItems + elements.length > data.length)
          {  // Ensure twice as much space as we need.
             ensureCapacity((manyItems + elements.length)*2);
          }
     
          System.arraycopy(elements, 0, data, manyItems, elements.length);
          manyItems += elements.length;
       }
     
     
     
       public void addAll(GenOrderedSet<E> addend)
       {
          // If addend is null, then a NullPointerException is thrown.
          // In the case that the total number of items is beyond
          // Integer.MAX_VALUE, there will be an arithmetic overflow and
          // the bag will fail.
          ensureCapacity(manyItems + addend.manyItems);
     
          System.arraycopy(addend.data, 0, data, manyItems, addend.manyItems);
          manyItems += addend.manyItems;
       }   
     
     
     
       public GenOrderedSet<E> clone( )
       {  // Clone an GenOrderedSet object.
          GenOrderedSet<E> answer;
     
          try
          {
             answer = (GenOrderedSet<E>) super.clone( );
          }
          catch (CloneNotSupportedException e)
          {  // This exception should not occur. But if it does, it would probably
             // indicate a programming error that made super.clone unavailable.
             // The most common error would be forgetting the "Implements Cloneable"
             // clause at the start of this class.
             throw new RuntimeException
             ("This class does not implement Cloneable");
          }
     
          answer.data = data.clone( );
     
          return answer;
       }
     
     
     
       public int countOccurrences(E target)
       {
          int answer;
          int index;
     
          answer = 0;
          for (index = 0; index < manyItems; index++)
             if (target == data[index])
                answer++;
          return answer;
       }
     
     
     
       public void ensureCapacity(int minimumCapacity)
       {
          E biggerArray[ ];
     
          if (data.length < minimumCapacity)
          {
             biggerArray = (E[]) new Object[minimumCapacity];
             System.arraycopy(data, 0, biggerArray, 0, manyItems);
             data = biggerArray;
          }
       }
     
     
     
       public int getCapacity( )
       {
          return data.length;
       }
     
     
     
       public E grab( )
       {
          int i;
     
          if (manyItems == 0)
             throw new IllegalStateException("Bag size is zero");
     
          i = (int)(Math.random( ) * manyItems) + 1;
          return data[i];
       }
     
     
       public boolean remove(E target)
       {
          int index; // The location of target in the data array.
     
          // First, set index to the location of target in the data array,
          // which could be as small as 0 or as large as manyItems-1; If target
          // is not in the array, then index will be set equal to manyItems;
          if (target == null)
          {  // Find the first occurrence of the null reference in the bag.
    	 index = 0;
    	 while ((index < manyItems) && (data[index] != null))
                index++;
          }
          else
          {  // Find the first occurrence of the target in the bag.
    	 index = 0;
    	 while ((index < manyItems) && (!target.equals(data[index])))
                index++;
          }
     
          if (index == manyItems)
             // The target was not found, so nothing is removed.
             return false;
          else
          {  // The target was found at data[index].
             // So reduce manyItems by 1 and copy the last element onto data[index].
             manyItems--;
             data[index] = data[manyItems];
    	 data[manyItems] = null;
             return true;
          }
       }
     
     
       public int size( )
       {
          return manyItems;
       }
     
     
     
       public void trimToSize( )
       {
          E trimmedArray[ ];
     
          if (data.length != manyItems)
          {
             trimmedArray = (E[]) new Object[manyItems];
             System.arraycopy(data, 0, trimmedArray, 0, manyItems);
             data = trimmedArray;
          }
       }
     
     
       public String toString()
       { StringBuilder s = new StringBuilder();
       s.append("GenOrderedSet[");
       for (int k = 0; k < size(); k++)
       {
       s.append(data[k]);
       // don't put comma after last element
       if (k != size() - 1)
       s.append(",");
       }
       s.append("]");
       return s.toString();
       }
     
    }

    and the tester:

    import java.util.Scanner;
     
     
    public class tester {
     
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		GenOrderedSet<String> create = new GenOrderedSet<String>();
            System.out.println("Add Intergers to bag put a negative to stop");
            Scanner re = new Scanner(System.in);
            String j = re.next();
            for(int i = 0; i < 5; i++){       
            j = re.next();
            create.add(j);
            System.out.println(create);
            }
            System.out.println("Please enter any intergers to remove put a negative when doene");
            String k = re.next();
     
                create.remove(k);        
            System.out.println(create.toString());
     
    	}
     
    }


  2. #2
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: Generics problem

    Even though I only have a year's worth of experience, I'm going to try and help out since there hasn't been a reply yet.

    I'm going to assume that you want to compare the data within the GenOrderedSet, and not the Set itself. Right now, it seems like you're trying to make the Generic data within the Set extend Comparable<E>, which won't necessarily work. That's why you can't cast Object into Comparable. Simply leave out the extends Comparable<E> and leave it as GenOrderedSet<E>. Whatever type of data you place within this Set must implement Comparable<Class_Name> in it's own Class declaration. Hopefully this helps a bit.
    Last edited by Staticity; July 16th, 2012 at 01:56 PM.
    Simplicity calls for Complexity. Think about it.

Similar Threads

  1. Generics
    By Kerr in forum Collections and Generics
    Replies: 2
    Last Post: May 19th, 2011, 06:44 PM
  2. Generics and Dynamic Instantiation Problem
    By marcosmarcos in forum Collections and Generics
    Replies: 2
    Last Post: March 4th, 2011, 02:32 PM
  3. Generics problem
    By ankur.trapasiya in forum Collections and Generics
    Replies: 1
    Last Post: January 22nd, 2011, 02:52 PM
  4. Generics
    By _lithium_ in forum What's Wrong With My Code?
    Replies: 21
    Last Post: December 6th, 2010, 07:08 PM
  5. Custom Java stack class (with generics) problem
    By TBBucs in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 7th, 2010, 02:25 AM

Tags for this Thread