简体   繁体   English

Java最佳实践 - 返回对象与通用

[英]Java Best Practices - Returning an Object vs. a Generic

I'm using Generics for the first time for a school project and I have come across a philosophical dilemma regarding whether to return objects or my declared generic element in my methods. 我第一次在学校项目中使用泛型,我遇到了一个关于是否在我的方法中返回对象或我声明的泛型元素的哲学困境。

My OCD is telling me that I need to always return the known type but I'm finding that doing so creates some downstream annoyances when I feed primitive datatypes into my class (and, of course, for this project I'm only ever feeding primitives into this class). 我的OCD告诉我,我需要始终返回已知的类型,但我发现当我将原始数据类型提供给我的类时,这样做会产生一些下游烦恼(当然,对于这个项目,我只会提供原语进入这个班)。

Here's an example of what I mean: 这是我的意思的一个例子:

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

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

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

(As an FYI.. I'm required to implement this JDK class myself but I am fortunately not required to implement the same interfaces that the real PriorityQueue does so I do have a choice as to whether I want to use the Object or the generic) (作为一个FYI ..我需要自己实现这个JDK类,但幸运的是我不需要实现真正的PriorityQueue所做的相同接口,所以我可以选择是否要使用Object或者泛型)

My Issue 我的问题

It makes me feel a little dirty but I'm tempted just to return an Object rather than my E generic element on these methods because when I return E, JUnit forces me to cast my integer values: 它让我觉得有点脏,但我很想在这些方法上返回一个Object而不是我的E泛型元素,因为当我返回E时,JUnit强制我强制转换整数值:

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

When I return an object on the other hand, the auto-boxing doesn't force me cast my primitive value. 另一方面,当我返回一个对象时,自动装箱不会强迫我施放原始值。

Here's a more eloquent description of the issue I've been facing: 以下是我所面临的问题的更有说服力的描述:

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

------------EDIT---------------- - - - - - - 编辑 - - - - - - - -

Here's the actual error I receive when I return the generic type and fill my list with the autoboxed Integer object without the cast above: The method assertEquals(String, Object, Object) is ambiguous for the type DansPriorityQueueTest 这是我返回泛型类型并使用自动装箱的Integer对象填充我的列表而没有上面的强制转换时收到的实际错误:方法assertEquals(String,Object,Object)对于DansPriorityQueueTest类型是不明确的

--------- END EDIT-------------- ---------结束编辑--------------

Questions 问题

  1. Can anyone tell me why I should or should not return an object as opposed to the generic element I'm working with? 谁能告诉我为什么我应该或不应该返回一个对象而不是我正在使用的通用元素? Both seem to have upsides and downsides... what's the best practice? 两者似乎都有好处和缺点......什么是最佳做法?

  2. I know vaguely that returning an Object can cause some casting issues later on but I've not yet run into them... does anyone have a specific example of how this can be dangerous? 我隐约知道返回一个Object可能会导致一些转换问题,但我还没有碰到它们......有没有人有一个具体的例子说明这可能是危险的?

  3. In the JDK, I've noticed that many of the Collections methods return Object by default. 在JDK中,我注意到许多Collections方法默认返回Object。 Is this because Generics was introduced in a later version of Java or was this a conscious decision by Sun Systems? 这是因为Generics是在Java的更高版本中引入的还是Sun Systems的有意识的决定?

Can anyone tell me why I should or should not return an object as opposed to the generic element I'm working with? 谁能告诉我为什么我应该或不应该返回一个对象而不是我正在使用的通用元素? Both seem to have upsides and downsides... what's the best practice? 两者似乎都有好处和缺点......什么是最佳做法?

It depends. 这取决于。 In a case like this you'd want to generic type - otherwise what's the point of defining generic type for the class? 在这种情况下,您需要泛型类型 - 否则为类定义泛型类型有什么意义?

I know vaguely that returning an Object can cause some casting issues later on but I've not yet run into them... does anyone have a specific example of how this can be dangerous? 我隐约知道返回一个Object可能会导致一些转换问题,但我还没有碰到它们......有没有人有一个具体的例子说明这可能是危险的?

Sure! 当然!

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

In the JDK, I've noticed that many of the Collections methods return Object by default. 在JDK中,我注意到许多Collections方法默认返回Object。 Is this because Generics was introduced in a later version of Java or was this a conscious decision by Sun Systems? 这是因为Generics是在Java的更高版本中引入的还是Sun Systems的有意识的决定?

It's due to backward compatibility mostly, or for cases where you truly will use the collection to contain disparate values (a mishmash of say, JLabels, Strings and Icons for instance for rendering a JTable for instance). 这主要是由于向后兼容性,或者是因为你真正使用该集合来包含不同的值(例如,例如JLabels,字符串和图标,例如用于渲染JTable)。

assertEquals("Expected different size", (Integer) 2, dpq.size()); assertEquals(“预期的不同大小”,(整数)2,dpq.size());

I don't think this should be a problem. 我不认为这应该是一个问题。 dpq.size() should just return an int regardless off what is stored in the priority queue. dpq.size()应该只返回一个int,而不管优先级队列中存储的是什么。 It would not be a generic value. 它不是一般价值。

You can create something like 你可以创造类似的东西

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

and that should cause no issues, right? 这应该没有问题,对吧?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java对象返回类型与通用方法 - Java Object return type vs. Generic Methods 吸气剂,制定者和属性最佳实践。 Java与C# - Getters, setters, and properties best practices. Java vs. C# 方法签名最佳实践 - 重载与长名称 - Method signature best practices - overloading vs. long name 通用编程与通用对象类型 - Generic Programming vs. General Object type 从 Restful 服务返回时的最佳实践 - 返回 Java Object 与返回手动构建的 JSON - Best practice when returning from Restful services - returning Java Object vs returning manually constructed JSON Java generics:设置与设置<object><div id="text_translate"><p>在 Java 中,将变量声明为Set与Set&lt;Object&gt;有什么区别? 两者不应该是等价的吗? 为什么将Set&lt;Object&gt;变量分配给Set时会出现编译时错误?</p></div></object> - Java generics: Set vs. Set<Object> Java中的类加载与对象创建 - Class Loading vs. Object creation in Java Java对象创建与字符串解析 - Java Object creation vs. String parsing Java集合与手动循环-编码挑战/面试最佳实践 - Java collections vs manual loops - Coding challenges/interview best practices 使用Java的OneToMany的最佳实践 - Best practices for OneToMany with Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM