您的位置:首页 > 其它

向集合中存储自定义对象是,自定义对象的设计

2015-06-28 21:29 387 查看
自定义对象

  通过对List、Set、Map 集合的操作,发现集合的不同,自定义类的定义也有所差异

1、List集合中的自定义对象

  由于List底层判断集合是否相同依赖的是equals方法,所以在自定义类时要覆盖equals方法

  示例:

//自定义类Person
class Person{
private String name;
private int age;
Person(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public boolean  equals(Object obj){
if( !(obj instanceof Person))
return false;
Person p = (Person) obj;
return this.name.equals(p.name) && this.age == p.age;//通过姓名和年龄,判断是否为同一个对象
}

}


2.HashSet类时自定义类  

  由于HashSet底层数据结构式哈希表,所以,通过hadhcode值和equals方法来判断对象是否相同

示例:

class Student{
private String name;
private int age;
Student(String name, int age){
this.name = name;
this.age = age;
}
public int hashCode(){
//System.out.println(this.name+"......hasCode");
return name.hashCode()+ age*39;
}
public boolean equals(Object obj){
if(!(obj instanceof Student))
return false;
Student stu = (Student)obj;
//System.out.println(this.name + "equals"+ stu.name);
return this.name.equals(stu.name) && this.age==stu.age;
}

public String toString(){
return name+"......"+age;
}
}


  

3.TreeSet类存储自定义类时

  由于TreeSet底层是二叉树数据结构,所以使用compareTo方法判断是否为同意对象;其有两种方式;

方式一:

  通过实现Compareable接口,覆盖compareTo方法;

示例:

class Studnet_2 implements Comparable<Object>{
private String name;
private int age;
Studnet_2(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
//根据StreeSet底层数据结构,集合通过compareTo 方法实现元素一致性
public int compareTo(Object obj){
if(!(obj instanceof Studnet_2))
throw new RuntimeException("这不是学生对象");
Studnet_2 stu = (Studnet_2)obj;
if(this.age > stu.age)
return 1;
if(this.age == stu.age)
return this.name.compareTo(stu.name);
return -1;
}

}


 

方式二:

通过定义比较器实现;

示例:

  

class StrLenComparator implements Comparator//比较器
{
public int compare(Object o1,Object o2)
{
String s1 = (String)o1;
String s2 = (String)o2;

if(s1.length()>s2.length())
return 1;
if(s1.length()==s2.length())
return 0;
int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
if(num==0)
return s1.compareTo(s2);

return num;
}
}


  

总结:当需要将自定义类对象作为参数存入到集合中时,一定要考虑到集合底层的数据结构,以便规范自定义类;

    同时,在开发过程中,自定义类似最好覆盖原有的比较方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: