生活随笔
收集整理的這篇文章主要介紹了
ArrayList排序-冒泡
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
將ArrayList<實體類>根據(jù)實體類中的指定元素進行排序
創(chuàng)建實體類
創(chuàng)建實體類,設(shè)置每一個屬性的get,set方法,并重寫toString方法
private String stuName
;private int stuAge
;private double stuGrade
;public String
getStuName() {return stuName
;}public void setStuName(String stuName
) {this.stuName
= stuName
;}public int getStuAge() {return stuAge
;}public void setStuAge(int stuAge
) {this.stuAge
= stuAge
;}public double getStuGrade() {return stuGrade
;}public void setStuGrade(double d
) {this.stuGrade
= d
;}@Overridepublic String
toString() {return "\t" + stuName
+ "\t" + stuAge
+ "\t" + stuGrade
;}
創(chuàng)建數(shù)據(jù)庫,獲取數(shù)據(jù)表中的值,并set
根據(jù)需要的信息創(chuàng)建一個數(shù)據(jù)庫:(添加測試值)
ArrayList
<StuInfo> arrayList
=new ArrayList<StuInfo>();
Class
.forName("com.mysql.jdbc.Driver");
Connection connection
=DriverManager
.getConnection
("jdbc:mysql://localhost:3307/stuinformation", "root", "123456");
StringBuffer sb
=new StringBuffer("select * from student");
PreparedStatement preparedStatement
=connection
.prepareStatement(sb
.toString());
ResultSet resultSet
=preparedStatement
.executeQuery();
StuInfo stuInfo
=null
;
while(resultSet
.next()) {stuInfo
=new StuInfo();stuInfo
.setStuName(resultSet
.getString(1));stuInfo
.setStuAge(resultSet
.getInt(2));stuInfo
.setStuGrade(resultSet
.getDouble(3));arrayList
.add(stuInfo
);
}
resultSet
.close();
preparedStatement
.close();
connection
.close();
return arrayList
;
轉(zhuǎn)換數(shù)組,冒泡排序
StuInforSort stuInforSort
=new StuInforSort();@Testpublic void show() throws Exception
{ArrayList
<StuInfo> arrayList
=stuInforSort
.getAllInfor();StuInfo
[]stuInfos
=new StuInfo[arrayList
.size()];arrayList
.toArray(stuInfos
);for(int i
=0;i
<stuInfos
.length
-1;i
++) {for(int j
=0;j
<stuInfos
.length
-i
-1;j
++) {if(stuInfos
[j
].getStuGrade()<stuInfos
[j
+1].getStuGrade()) {StuInfo temp
=stuInfos
[j
];stuInfos
[j
]=stuInfos
[j
+1];stuInfos
[j
+1]=temp
;}}}System
.out
.println("排名\t姓名\t年齡\t成績");int count
=1;for(StuInfo s
:stuInfos
) {System
.out
.println(count
+""+s
);count
++;}}
總結(jié)
以上是生活随笔為你收集整理的ArrayList排序-冒泡的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。