什么时候在java中使用Long vs long?

AKI*_*WEB 21 java constructor map

以下是我的界面 -

public interface IDBClient {
    public String read(ClientInput input);
}
Run Code Online (Sandbox Code Playgroud)

这是我的接口实现 -

public class DatabaseClient implements IDBClient {

    @Override
    public String read(ClientInput input) {

    }
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个工厂得到这样的实例DatabaseClient-

IDBClient client = DatabaseClientFactory.getInstance();
....
Run Code Online (Sandbox Code Playgroud)

现在我需要调用readmy 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;
    }
}    
Run Code Online (Sandbox Code Playgroud)

因此,当客户调用read方法时DatabaseClient,他们将创建这样的ClientInput参数,然后使用工厂获取实例,DatabaseClient然后相应地调用read方法.

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);
Run Code Online (Sandbox Code Playgroud)

问题陈述:-

  1. 所以我的第一个问题是确实的userid,clientid,timeout_ms应该是Long对象或者只是longClientInput上课吗?
  2. 第二个问题我已经是,有可能是客户可以通过错误的信息,比如negative user ids,negative client id,negative timeout价值等等等等.那么,我应该这样做验证?我应该在ClientInput类的构造函数中还是在其他地方执行此验证检查?有什么更好的方法,我应该如何进行验证?

Boh*_*ian 43

long是一个原始的,必须有一个值.简单.

Long是一个对象,所以:

  • 它可以null(意思是你喜欢什么,但"未知"是一种常见的解释)
  • 它可以被传递到一个接受的方法Object,Number,Longlong参数(最后一个得益于自动拆箱)
  • 可以使用一个通用的参数类型,即List<Long>是确定的,但List<long>就是 OK
  • 它可以通过java序列化机制进行序列化/反序列化

始终使用最简单的工作方式,因此如果您需要任何功能Long,请使用Long否则使用long.a的开销Long非常小,但它确实存在.


Ste*_* B. 18

我认为没有一个正确的答案.一些建议:

  • 在这种情况下,我在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...
    }
    
    Run Code Online (Sandbox Code Playgroud)

    最终,validationException仅在你可以用它做一些有用的东西时才能捕获它 - 将它回显给用户或其他任何东西.