小编L.S*_*ner的帖子

构造函数重载 - Java中的最佳实践

构造函数也可以像任何其他方法一样重载,我知道这个事实.由于任务,我决定使用具有多个构造函数的抽象超类:

摘要超类:

protected ListSortierer()
{
  this( null, null );
}

protected ListSortierer( List<E> li )
{
  this( li, null );
}

protected ListSortierer( Comparator<E> comp )
{
  this( null, comp );     
}

protected ListSortierer( List<E> li, Comparator<E> com )
{
  this.original = Optional.ofNullable( li );
  this.comp = Optional.ofNullable( com );
}
Run Code Online (Sandbox Code Playgroud)

要访问每个构造函数,我还需要子类中的多个构造函数.

BubbleSort.java:

public ListBubbleSort()
{
  super();
}

public ListBubbleSort( List<E> li )
{
  super( li );
}

public ListBubbleSort( Comparator<E> com )
{
  super( com );
}

public ListBubbleSort( …
Run Code Online (Sandbox Code Playgroud)

java inheritance constructor instance superclass

17
推荐指数
2
解决办法
1669
查看次数

为什么.equals()方法不会覆盖Java中的基元数组?

我目前正在开发一个项目,我希望使用用户名和密码与数据库进行比较来实现登录机制.

我有这样的想法:

public boolean verifyUser( String username, char[] password ) 
{
  List<char[]> dbpass = getPasswords( username );
  if ( dbpass.contains( password ) )
  {
    overwriteWithNonsense( password );
    return true;
  }
  overwriteWithNonsense( password );
  return false;
}
Run Code Online (Sandbox Code Playgroud)

当我注意到我的单元测试失败了.所以我把它一个更深入的了解发现,该Object::equals方法没有覆盖这解释了为什么基本类型数组List::contains始终评估为false.

我知道有一种可能的解决方法:

if ( dbpass.stream().anyMatch( pw -> Arrays.equals( pw, password ) ) )
{
  overwriteWithNonsense( password );
  return true;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么设计师选择保留"默认实现" Object::equals?使用静态实用程序方法实现框架不是更方便Arrays.equals(array1,array2)吗?

java arrays language-design equals

10
推荐指数
1
解决办法
262
查看次数