4、单双列集合

2019-06-20  本文已影响0人  浮生若梦OvO

一、定义

集合只用于存储对象,集合长度是可变的,集合可以储存不同类型的数据,集合中存储的是对象的引用(地址值)。

二、Collection接口(单列集合顶层接口)

三、Collection接口中的功能概述

四、Collection接口的子接口List

1、全部通过迭代器操作,使用列表迭代器
代码: 
     ListIterator lit = list.listIterator();
            while ( lit.hasNext()) {
                String s = (String) lit.next();
                 if ( "hello".equals( s)) {
                      lit.add("IOS");//全部通过迭代器操作:元素是添加到刚遍历的那个元素后面。
                }
           }
2、全部通过集合操作:
代码:
for ( int x = 0; x < list.size(); x++) {
                String s = (String) list.get( x);
                 if ( "hello".equals( s)) {
                      list.add("IOS");//元素是添加到最后的。
                }
           }

五、ArrayList概述

六、Vector集合(Vector的特有功能)

七、LinkedList

八、Collection接口的另一个子接口Set

复写: hashCode()方法
public int hashCode()

     
 final int prime = 31;

     
 int result = 1;

    
  result = prime * result + age;

     
  result = prime * result + ((name == null) ? 0 : name.hashCode());

     
  return result;

     
  }
     

复写:equals(Object obj)方法
public boolean equals(Object obj) {

     
 if (this == obj)

     
 return true;

     
 if (obj == null)

     
  return false;

     
 if (getClass() != obj.getClass())

      
 return false;

     
 Student other = (Student) obj;

     
  if (age != other.age)

     
 return false;

     
 if (name == null) {

     
 if (other.name != null)

     
 return false;

     
 } else if (!name.equals(other.name))

     
  return false;

     
 return true;

     
  }
public int compareTo( Studetn s )
{
     //需求是比较年龄
     int num = this.age - s.age ;
     //当某一个相同的时候,你还需要判断其他的是不是也是相同的。
     int num2 = ( num == 0 ) ? ( this.name.compareTo( s.name ) ) : num ;
     return num2;
}
a:定义一个比较器实现Compareator接口
 class MyComparator implements Comparator<Student>{
     
public int compare(Student s1,Student s2){
           
 int num = s1.getName().length() -  s2.getName().length();
           
 int num1 = ( num == 0) ? (s1.getName().compareTo( s2.getName())) : num;
           
 int num2 = ( num1 == 0) ? ( s1.getAge() - s2.getAge()) : num1;
           
 return num2 ;
     }

}
b:在内部类中实现比较器:
TreeSet<Student>
 ts = new TreeSet<Student>( new Comparator<Student>() {
                
 @Override
                
 public int compare(Student s1, Student s2) {
                     
 int num = s1.getName().length() - s2.getName().length();
                     
 int num1 = ( num == 0) ? (s1.getName().compareTo( s2.getName())): num;
                     
 int num2 = ( num1 == 0) ? ( s1.getAge() - s2.getAge()) : num1;
                     
 return num2;
                }
           } );

九、Map接口(双列集合的顶层接口)

上一篇 下一篇

猜你喜欢

热点阅读