有没有一种方法可以在Java中计算LocalDate中的最小值?

huangapple go评论68阅读模式
英文:

Is there a way to calculate the smallest value from a LocalDate in java?

问题

我正在处理一个Java的作业,其中我有一个Prisoner类,其中有犯罪日期(dd-MM-yyyy)的LocalDate格式、姓名和监禁年限。我还有一个Cell类,我必须在其中将囚犯添加到监狱牢房。

我必须创建一个方法来显示应该首先释放哪个囚犯。

不幸的是,我不知道该如何做。我已经为将囚犯添加到牢房的方法编写了代码,我使用了HashSet,但我不知道如何计算谁应该首先被释放。

以下是我用于添加囚犯的代码:

public Boolean addPrisoner(Prisoner prisoner) {
  if (this.prisonerList.size() <= this.cellSize) {
    return this.prisonerList.add(prisoner);
  }
  return false;
}
英文:

I am working on an assignment in java where I have Prisoner class which have date of offence (dd-MM-yyyy) localDate format, name and years in prison. I also have Cell class where I have to add prisoners in the cell.

I have to make a method to show which Prisoner should be release first from the Cell.

Unfortunately, I have no idea how to do that. I already made a method for adding the prisoners in the cell and I use HashSet but I have not idea how to calculate who should be released first.

This is my code for adding the prisoners

public Boolean addPrisoner(Prisoner prisoner) {
  if (this.prisonerList.size() &lt;= this.cellSize) {
    return this.prisonerList.add(prisoner);
  }
  return false;
}

答案1

得分: 0

请参考以下翻译:

让您的囚犯自行计算其释放日期(在现实生活中,这可能会引诱计算欺诈性的释放日期,但只要您编写了该方法,在Java程序中就没问题)。例如:

public class Prisoner {
    
    private LocalDate dateOfOffence;
    private int yearsOfSentence;
    
    public LocalDate getReleaseDate() {
        return dateOfOffence.plusYears(yearsOfSentence);
    }
    
}

现在,Collections.min 可以找到拥有最早释放日期的囚犯:

Prisoner nextPrisonerToBeReleased = Collections.min(
        prisonerList, Comparator.comparing(Prisoner::getReleaseDate));
英文:

Have your prisoner calculate his or her own release date (in real life this might tempt to calculate fraudulent release dates, but as long as you write the method, it’s OK in a Java program). For example:

public class Prisoner {

	private LocalDate dateOfOffence;
	private int yearsOfSentence;
	
	public LocalDate getReleaseDate() {
		return dateOfOffence.plusYears(yearsOfSentence);
	}
	
}

Now Collections.min can find the prisoner having the earliest release date:

		Prisoner nextPrisonerToBeReleased = Collections.min(
				prisonerList, Comparator.comparing(Prisoner::getReleaseDate));

huangapple
  • 本文由 发表于 2020年10月16日 22:27:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64391107.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定