前言
今天在做项目时,遇到排序,一直用TreeSet,导致钻进了死胡同,最后选择用List解决。
详情可看这里https://blog.csdn.net/A567500/article/details/129882830
目录
一、List
List的特点是有序可重复,如果要求排序的对象不重复,可在创建的对象中声明equals方法
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MovieScore that = (MovieScore) o;
//如果名字一样,将不插入
return Objects.equals(movieName, that.movieName);
}
二、代码
1.对象代码
package com.llpy.bean;
import java.util.Objects;
public class MovieScore {
private String movieName;
private double Score;
private double ScoreSum;
private int count = 0;
public MovieScore() {
}
public MovieScore(String movieName, double score, int count,double scoreSum) {
this.ScoreSum = scoreSum;
this.movieName = movieName;
Score = score;
this.count = count;
}
public double getScoreSum() {
return ScoreSum;
}
public void setScoreSum(double scoreSum) {
ScoreSum = scoreSum;
}
public String getMovieName() {
return movieName;
}
public void setMovieName(String movieName) {
this.movieName = movieName;
}
public double getScore() {
return Score;
}
public void setScore(double score) {
Score = score;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MovieScore that = (MovieScore) o;
return Objects.equals(movieName, that.movieName);
}
@Override
public int hashCode() {
return Objects.hash(movieName, Score, ScoreSum, count);
}
@Override
public String toString() {
return "MovieScore{" +
"movieName='" + movieName + '\'' +
", Score=" + Score +
", ScoreSum=" + ScoreSum +
", count=" + count +
'}';
}
}
2.运行代码
//先声明一个常量 存放所有电影分数
public static final List<MovieScore> ALL_SCORE = new ArrayList<>();
//声明一个用作判断的数;
public static int count = 0;
//测试数据
MovieScore movieScore1 = new MovieScore("1",9,1,9);
MovieScore movieScore2 = new MovieScore("2",9,1,9);
MovieScore movieScore3 = new MovieScore("3",9,1,9);
MovieScore movieScore4 = new MovieScore("4",9,1,9);
Collections.addAll(ALL_SCORE,movieScore1,movieScore2,movieScore3,movieScore4);
//运行
while (true) {
System.out.println("请输入要进行评分的电影名称:");
String movieName = SYS_SC.nextLine();
count = 0;
for (MovieScore movieScore : ALL_SCORE) {
if(movieScore.getMovieName().equals(movieName)){
count++;
while (true) {
System.out.println("请输入您的评分(0-10):");
double score = Double.parseDouble(SYS_SC.nextLine());
if(score>=0 && score<=10){
//得到现在的总分
double sum = score+movieScore.getScoreSum();
//得到评论过的人数
int count1 = movieScore.getCount();
count1=count1+1;
//得到最总分数
double newScore = sum/ count1;
//将新的结果更新
movieScore.setScore(newScore);
movieScore.setCount(count1);
movieScore.setScoreSum(sum);
//重新根据分数排序
ALL_SCORE.sort((MovieScore o1, MovieScore o2)-> o1.getScore()-o2.getScore()>0?-1:1);
break;
}else{
System.out.println("输入的评分有误");
}
}
}
}
if(count==0){
System.out.println("输入的名称有误,请重试");
}else{
reak;
}
}
在改用ArraysList进行排序后,之前的问题全部解决!
总结
在对需要修改的对象排序时,不要用TreeSet,改用ArraysList。