码迷,mamicode.com
首页 > 其他好文 > 详细

黑马程序员-学习日记(集合类之TreeSet)

时间:2014-11-23 17:24:31      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   java   

为什么会用到集合类?

面向对象语言对事物的体现都是以对象的方式,所以为了方便对多个对象的操作,就对对象进行存储,集合就是存储对象最常用的一种方式。                                  

数组虽然也可以存储对象,但长度固定。集合长度可变。数组中可以存储基本数据类型,集合只能存储对象。

集合类自身的特点

只用于存储对象,长度可变,能够存储不同类型的对象。

容器分了很多种,因此Java工程师对其进行了划分。这个划分成的体系就被成为集合框架。

import java.util.*;
class mapDemo
{
    public static void main(String[] args) 
    {
        TreeSet ts = new TreeSet();
        ts.add(new student("Truson",22));
        ts.add(new student("Amy",21));
        ts.add(new student("Ben",19));
ts.add(new student("Boston",19)); Iterator it
= ts.iterator(); while(it.hasNext()) { student s = (student)it.next(); System.out.println(s); } } } class student implements Comparable { String name; int age; student(String name,int age) { this.name = name; this.age = age; } int getAge() { return age; } String getName() { return name; } }

bubuko.com,布布扣

 能通过编译,但运行时报出了异常。原来TreeSet可以对Set集合中元素按字母顺序进行排序。但集合中若是存入了对象,程序就不知道依据什么标准对元素进行排序。此时的对象不具备比较性,从而报出异常。于是查阅API后发现必须要实现一接口Comparable<T>,此接口强制让学生具备比较性。

于是更改代码如下:

import java.util.*;
class mapDemo
{
    public static void main(String[] args) 
    {

        TreeSet ts = new TreeSet();
        ts.add(new student("Truson",22));
        ts.add(new student("Amy",21));
        ts.add(new student("Ben",19));
Iterator it
= ts.iterator(); while(it.hasNext()) { student s = (student)it.next(); System.out.println(s); } } } class student implements Comparable { String name; int age; student(String name,int age) { this.name = name; this.age = age; } int getAge() { return age; } String getName() { return name; } public int compareTo(Object obj) { if(!(obj instanceof student)) throw new RuntimeException("不是学生对象!"); student stu = (student)obj; System.out.println(this.name+" compare to "+stu.name); if(this.age > stu.age) return 1; if(this.age < stu.age) return -1; return 0; } }

 显然,这个时候我们可以实现依照学生的年龄排序了。但依然存在问题,因为如果有两个学生年龄一样而姓名不同,便只能保存先出现的那个。于是再次修改代码。

if(this.age == stu.age)
        {
            //当主要条件相同,判断次要条件
            return this.name.compareTo(s.name);
        }

 

黑马程序员-学习日记(集合类之TreeSet)

标签:style   blog   http   io   ar   color   os   sp   java   

原文地址:http://www.cnblogs.com/tozr/p/4116623.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!