生活随笔
收集整理的這篇文章主要介紹了
ArrayList排序-冒泡
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
將ArrayList<實體類>根據實體類中的指定元素進行排序
創建實體類
創建實體類,設置每一個屬性的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
;}
創建數據庫,獲取數據表中的值,并set
根據需要的信息創建一個數據庫:(添加測試值)
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
;
轉換數組,冒泡排序
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
++;}}
總結
以上是生活随笔為你收集整理的ArrayList排序-冒泡的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。