guys, I have declare a generic array in OrderSet class; however, during compilation is giving me an error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable; at wordset.OrderSet.<init>(OrderSet.java:17) at wordset.Main.main(Main.java:20) Java Result: 1
main
public class Main { public static void main(String[] args) throws IOException { OrderSet<String> s1 = new OrderSet<>(); String fileName; Scanner in = new Scanner(System.in); System.out.println("Enter the name of the input file"); fileName = in.next(); File inFile = new File(fileName); Scanner input; try { input = new Scanner(inFile); while (input.hasNext()) { String w = input.next(); s1.add(w); } } catch (FileNotFoundException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } s1.show(); } }
public interface Set<T> { public void add(T x); public void show(); }
import java.util.Arrays; public class OrderSet<T extends Comparable> implements Set<T> { private T[] items; private int size; public OrderSet() { items = (T[]) new Object[5]; } @Override public void add(T s) { if(size >= items.length) { items = grow(items); } for (int i = 0; i < items.length; i++) { if(items[i] == null) { items[i] = s; size++; break; } } } @Override public void show() { int i = 0; while(i < size) { System.out.print(items[i]+", "); i++; } } public T[] grow(T[] a) { T[] newA = (T[]) new Object[a.length+5]; System.arraycopy(a, 0, newA, 0, a.length); return newA; } }