什么时候在 Java 中使用 Long 和 long?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21034955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When to use Long vs long in java?
提问by AKIWEB
Below is my Interface -
下面是我的界面 -
public interface IDBClient {
public String read(ClientInput input);
}
This is my Implementation of the Interface -
这是我的接口实现 -
public class DatabaseClient implements IDBClient {
@Override
public String read(ClientInput input) {
}
}
Now I have a factory which gets the instance of DatabaseClient
like this -
现在我有一个工厂,它得到这样的实例DatabaseClient
-
IDBClient client = DatabaseClientFactory.getInstance();
....
Now I need to make a call to read
method of my DatabaseClient
which accepts the ClientInput
parameter and below is the class for the same. This class was not written by me so that is the reason I am having a question on this and I am pretty much sure this is the wrong way of doing it.
现在我需要调用read
我的方法,DatabaseClient
它接受ClientInput
参数,下面是相同的类。这门课不是我写的,所以这就是我对此有疑问的原因,我很确定这是错误的做法。
public final class ClientInput {
private Long userid;
private Long clientid;
private Long timeout_ms = 20L;
private boolean debug;
private Map<String, String> parameterMap;
public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout_ms, boolean debug) {
this.userid = userid;
this.clientid = clientid;
this.parameterMap = parameterMap;
this.timeout_ms = timeout_ms;
this.debug = debug;
}
}
So when customer make a call to read
method of DatabaseClient
, they will create the ClientInput
parameter like this and then use the factory to get the Instance of DatabaseClient
and then call the read method accordingly.
所以当客户调用read
方法时DatabaseClient
,他们会ClientInput
像这样创建参数,然后使用工厂获取实例,DatabaseClient
然后相应地调用读取方法。
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("attribute", "segmentation");
ClientInput input = new ClientInput(109739281L, 20L, paramMap, 1000L, true);
IDBClient client = DatabaseClientFactory.getInstance();
client.read(input);
Problem Statement:-
问题陈述:-
- So my first question is does the
userid
,clientid
,timeout_ms
should beLong
object or just simplylong
inClientInput
class? - Second question I have is, it might be possible that customer can pass wrong information such as
negative user ids
,negative client id
,negative timeout
value etc etc.. Then where I should do this validation? Should I do this validation check in the constructor ofClientInput
class or at some other place? What's the better way of doing this and how should I do the validation?
- 所以我的第一个问题是
userid
,clientid
,timeout_ms
应该是Long
对象还是只是long
在ClientInput
课堂上? - 第二个问题我已经是,有可能是客户可以通过错误的信息,比如
negative user ids
,negative client id
,negative timeout
价值等等等等。那么,我应该这样做验证?我应该在ClientInput
类的构造函数中还是在其他地方进行此验证检查?这样做的更好方法是什么,我应该如何进行验证?
采纳答案by Steve B.
I don't think there's a single correct answer. A few suggestions:
我认为没有一个正确的答案。几点建议:
The biggest difference I see between
long
andLong
in this context is thatLong
may benull
. If there's a possibility you might have missing values, theLong
object will be helpful asnull
can indicate missing values. If you're using primitives, you'll have to use some special value to indicate missing, which is probably going to be a mess. Speed or size is not likely to be an issue unless you're planning on making an array of a million of these things and then serializing.My preference for validation logic is to throw some sort of custom
ValidationException
at the point at which the thing could fail. If you're just creating these things with a constructor, the simplest thing would be just to validate there, e.g.public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout_ms, boolean debug) throws ValidationException { if (userid == null) throw new ValidationException("UserId is required"); ...etc, etc... }
在这种情况下,我在
long
和之间看到的最大区别可能是. 如果您可能有缺失值,该对象将很有帮助,因为它可以指示缺失值。如果您使用原语,则必须使用一些特殊值来表示缺失,这可能会造成混乱。速度或大小不太可能成为问题,除非您计划制作一百万个这样的数组,然后进行序列化。Long
Long
null
Long
null
我对验证逻辑的偏好是
ValidationException
在事情可能失败的地方抛出某种自定义。如果您只是使用构造函数创建这些东西,那么最简单的方法就是在那里进行验证,例如public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout_ms, boolean debug) throws ValidationException { if (userid == null) throw new ValidationException("UserId is required"); ...etc, etc... }
Ultimately, the ValidationException
is only useful if you can catch it at a point where you can do something useful with it - echo it back to a user or whatever.
最终,ValidationException
只有当您可以在可以用它做一些有用的事情的时候抓住它时,它才有用 - 将它回显给用户或其他任何东西。
回答by TwilightSun
1 Long is the object orientated counter part of long. The difference is as follows, and it applies to Float to float, Integer to integer etc.
1 Long 是long 的面向对象的对应部分。区别如下,适用于Float到float,Integer到integer等。
- long is a primitive type, while Long is a Java class (and so it will inherit Object).
- long must be assigned with a valid number, while Long can be null
- long instances can't use the benefits of OO, while instances of Long are real Java objects
- Long is a serializable so it will be very useful when doing file, database or network IO
- long is more efficient than Long considering memory space and processing speed
- long 是原始类型,而 Long 是 Java 类(因此它将继承 Object)。
- long 必须分配一个有效的数字,而 Long 可以为空
- long 实例不能利用 OO 的好处,而 Long 的实例是真正的 Java 对象
- Long 是可序列化的,因此在执行文件、数据库或网络 IO 时非常有用
- 考虑到内存空间和处理速度,long 比 Long 更有效
If you are doing heavy calculations, use primitive types. Otherwise if you're concerning more about design, the object counter parts will be very useful.
如果您正在进行大量计算,请使用原始类型。否则,如果您更关心设计,则对象计数器部件将非常有用。
2 Since you are not using any frameworks if I'm observing correctly, I suggest you make an interface like Validatedwith a method bool validate(). And every time you try to put a input into the database call validate in advance.
2 由于如果我观察正确,您没有使用任何框架,我建议您使用方法bool validate()制作一个类似Validated的接口。每次您尝试将输入放入数据库时,请提前验证。
回答by keshlam
1) Use Long if you need to treat the value as an object. Use long otherwise; it's more efficient.
1) 如果需要将值视为对象,请使用 Long。否则使用 long ;它更有效率。
2) Judgement call, really. Putting it deeper means you're going to check even when the value is coming from a source you trust, but that may catch errors in other code. Putting it closer to the user input means you lose that deep sanity-check (and may need to check in more than one place) but avoids spending time checking things you've already checked. What's best depends on how you plan on using/enhancing this code in the future.
2)判断电话,真的。更深入地讲意味着即使值来自您信任的来源,您也将进行检查,但这可能会捕获其他代码中的错误。把它放在更接近用户输入的地方意味着你失去了深度的健全性检查(并且可能需要在多个地方检查)但避免花时间检查你已经检查过的东西。什么是最好的取决于您计划如何在将来使用/增强此代码。
回答by Rugal
As
Long
is wrapper class privimitive typelong
andLong
is a class, which indicate its instance could be null. In my perspective use wrapper class is better than primitive type because there could havenull
state in it, which could tells us more information.
In addition, wrapper class will automatically initialized with 0, it is good for lazy using.For data validation, I think you'd better do it in
controller
rather thanDAO
, then have a good method to handle this or alert user to modify them!
作为
Long
包装类原始类型long
并且Long
是一个类,这表明它的实例可以为空。在我看来,使用包装类比原始类型更好,因为它可以包含null
状态,可以告诉我们更多信息。
另外,wrapper类会自动初始化为0,有利于懒人使用。对于数据验证,我认为您最好在
controller
而不是 中进行DAO
,然后有一个很好的方法来处理这个或提醒用户修改它们!
回答by slipperyseal
The advantage of the Long class is that the value can be null. In your case, if no Long ID is supplied, if you quickly detect this with something like..
Long 类的优点是值可以为空。在你的情况下,如果没有提供长 ID,如果你用类似的东西快速检测到这一点。
public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout_ms, boolean debug) {
if (userid == null) {
throw new IllegalArgumentException("userid is null");
}
To your second question, you could place your ID validation in the constructor as well. This ensures that if the ID is null or invalid, a ClientInput can never be created. But there is no "best" answer for where you put this validation, it depends on the structure of the rest of your code, but ideally you want to catch such things as early as possible.
对于您的第二个问题,您也可以将 ID 验证放在构造函数中。这确保如果 ID 为空或无效,则永远无法创建 ClientInput。但是对于放置此验证的位置没有“最佳”答案,这取决于其余代码的结构,但理想情况下您希望尽早捕获此类内容。
public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout_ms, boolean debug) {
if (userid == null || userid < USER_ID_MIN || userid > USER_ID_MAX ) {
throw new IllegalArgumentException("userid is invalid");
}
Another option is to accept the userid parameter as a Long, testing it for null, but then store it as a private, primitive long, once you know its valid.
另一种选择是接受 userid 参数作为一个 Long,测试它是否为空,然后将它存储为一个私有的、原始的 long,一旦你知道它是有效的。
回答by Bohemian
long
is a primitive, which musthave a value. Simple.
long
是一个原语,它必须有一个值。简单的。
Long
is an object, so:
Long
是一个对象,所以:
- it can be
null
(meaning whatever you like, but "unknown" is a common interpretation) - it can be passed to a method that accepts an
Object
,Number
,Long
orlong
parameter (the last one thanks to auto-unboxing) - it can be used an a generic parameter type, ie
List<Long>
is OK, butList<long>
is notOK - it can be serialized/deserialized via the java serialization mechanism
- 它可以是
null
(意思是任何你喜欢的,但“未知”是一种常见的解释) - 它可以被传递到一个接受的方法
Object
,Number
,Long
或long
参数(最后一个得益于自动拆箱) - 可以使用一个通用的参数类型,即
List<Long>
是确定的,但List<long>
就是不OK - 可以通过java序列化机制进行序列化/反序列化
Always use the simplest thing that works, so if you need any of the features of Long
, use Long
otherwise use long
. The overhead of a Long
is surprisingly small, but it is there.
始终使用最简单的方法,因此如果您需要 的任何功能Long
,请使用Long
其他方式使用long
。a 的开销Long
非常小,但它确实存在。
回答by as21
I try to keep Bean objects as simple as possible, which would mean handling validation elsewhere - either in a separate Validator class or in a validate() method. The general algorithm is the same:
我尽量保持 Bean 对象尽可能简单,这意味着在其他地方处理验证 - 在单独的 Validator 类中或在 validate() 方法中。一般算法是一样的:
- validateInputParametres()
- readDb()
- 验证输入参数()
- 读取数据库()
I would do something like:
我会做这样的事情:
final ClientInput input = new ClientInput(109739281L, 20L, paramMap, 1000L, true);
validate(input); // throw/handle exceptions here
final Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("attribute", "segmentation");
final IDBClient client = DatabaseClientFactory.getInstance();
client.read(input);