java contions_Java基础---数组总结
圖片比較大,可能看不太清楚,可以單擊右鍵選擇查看圖片,看大圖
這里截取截取幾個比較重要的展示吧,具體的大家看圖了
arraylist---類:數組實現,查找快,線程不安全,效率高,最常用的集合之一
去重:
//注意,自定義對象必須重寫 equals 方法才能實現去重
//因為 contions ();底層是依靠 equals 實現的
ArrayList a = new ArrayList();
a.add(new Student("張三",23));
a.add(new Student("張三",23));
a.add(new Student("李四",24));
//獲取迭代器對象
Iterator i = a.iterator();
//創建新集合
ArrayList a1 = new ArrayList();
while (i.hasNext()) {
Student s = i.next();//.next();有個指針不能連續調用
if (!a1.contains(s)) {
a1.add(s);
}
}
TreeSet---類:在保證數據唯一性的情況下對數據進行排序,排序的功能由二叉樹算法實現
兩種實現方法:
方法一:自定義對象實現compareable接口,并且重寫其中的compareTo方法
public class Student implements Comparable
@Override
public int compareTo(Student o) {
int num = this.age - o.age;
return num == 0 ? this.name.compareTo(o.name) : num;
}
自定義對象實現了該接口之后,直接傳入,TreeSet 集合就可以實現排序和去重
當我們要保留重復元素的時候可以這樣
return num == 0 ? 1 : num;
注意:
this.age - o.age; 是從小到大
o.age - this.age 是從到小
這跟二叉樹的算法有關,存法:返回值為負數存左邊,為正存右邊,為0不存
取法:默認先取左邊
方法二:在創建TreeSet對象的時候通過構造方法傳入比較器(實現了comparator的對象實例,一般通過匿名內部類實現)
TreeSet t = new TreeSet(new Comparator() {
@Override
public int compare(Student o1, Student o2) {
int num = o1.getAge() - o2.getAge();
return num == 0 ? o1.getName().compareTo(o2.getName()) : num;
}
});
我們一般是通過構造方法傳入 comparator 的匿名子類對象
o1.getAge() - o2.getAge(); 從小到大
o2.getAge() - o1.GetAge(); 從大到小
--------------------------------------------------------------------------------------------------------------------------------------------------------------
好了,我就寫這么多了,具體的大家看圖了啊
總結
以上是生活随笔為你收集整理的java contions_Java基础---数组总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 合并 set_【Java必修课
- 下一篇: java8 虚拟机调优_Java虚拟机调