Java recommendations - returning an object to the general

This is the first time I'm using Generics for a school project, and I am faced with a philosophical dilemma as to whether to return objects or my declared common element to my methods.

My OCD tells me that I always need to return a known type, but I find that it creates some trouble in the downstream when I feed the primitive data types into my class (and, of course, for this project I only ever feed primitives in this class).

Here is an example of what I mean:

public class DansPriorityQueue<E extends Comparable> 
{
    private ArrayList<E> tree;

//Here a method that returns an object
public Object peek() {
    return tree.get(0);
}

//Here a method that returns the generic type
public E peek() {
    return tree.get(0);
}

(Like FYI .. I need to implement this JDK class myself, but, fortunately, I do not need to implement the same interfaces as in the real PriorityQueue, so I have a choice as to whether I want to use Object or general)

My question

, , E , , E, JUnit :

DansPriorityQueue<Integer> dpq = new DansPriorityQueue<Integer>();
dpq.add(1);
assertEquals("Expected different value", (Integer) 1, dpq.peek());

, , .

, :

http://www.aschroder.com/2009/10/php-1-java-0-the-method-assertequalsobject-object-is-ambiguous-for-the-type/

------------ ----------------

, , Integer . assertEquals (String, Object, Object) DansPriorityQueueTest

--------- END EDIT --------------

  • - , , , ? , , ... ?

  • , , ... - , ?

    /li >
  • JDK , Collections Object . , Generics ​​ Java Sun Systems?

+4
1

- , , , ? , , ... ?

. - , ?

, , ... - , ?

!

DansPriorityQueue<String> queue = new DansPriorityQueue<String>();
//add items
Float f = (Float)queue.getObject();  //uh-oh! this compiles but will fail 
Float f = queue.getObject(); //generic type, fails during compile

JDK , Collections Object . , Generics ​​ Java Sun Systems?

, , (, mishmash, JLabels, Strings Icons JTable).

assertEquals ( " ", ( ) 2, dpq.size());

, . dpq.size() int , . .

-

DansPriorityQueue<Double> queue = new DansPriorityQueue<Double>();
for(double d = 0; d < 10; d+=1.0)
    queue.add(d);

, ?

+8

All Articles