欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

2020/3/31学习笔记-day30

程序员文章站 2022-06-12 15:41:57
...

java-day30

集合的使用总结

怎么往集合中放数据
怎么从集合中删除数据
怎么从集合中找数据
怎么循环遍历集合中所有数据

List接口的采用实现:

ArrayList 实现类

LinkedList 实现类

Vector 实现类

Set集合的实现类

HashSet直接实现了Set接口

Set还有一个子接口SortedSet(可以进行数据排序)

SortedSet下有一个常用的实现类TreeSet

Set/List接口的特点:

Set接口的特点 List接口的特点
无序不可重复 有序可重复
没有定义额外的抽象方法,都是从父接口中继承过来的 有自己新的方法
public class SetTest {
	
	public static void main(String[] args){
		SetTest x = new SetTest();
		x.test1();
	}

	public void test1(){
		Set set1 = new HashSet();
		set1.add("set1");
		set1.add("set2");
		set1.add("set3");
		set1.add("set4");
		set1.add("set5");
		this.showCollection(set1);
	}

	private void showCollection(Collection c){
		Iterator it = c.iterator();
		System.out.println("--------begin-----------");
		while(it.hasNext()){
			Object obj = it.next();
			System.out.println("\t"+obj);	
		}
		System.out.println("---------end------------");	
	}
} 

2020/3/31学习笔记-day30

Set是无重复的,且内部按照hashCode值来排序的(一般我们认为无序是因为hashCode不确定的)

//重写hashCode按照age
public void test2(){
    Set set =null;
    set = new HashSet();
    set.add(new Student(1L,"TOM",21));
    set.add(new Student(2L,"JACK",24));
    set.add(new Student(3L,"MARRY",22));
    set.add(new Student(4L,"JAMES",23));
    set.add(new Student(5L,"CURRY",20));
    set.add(new Student(5L,"CURRY",20));
    this.showCollection(set);
}
public int hashCode(){
    return age;
}

2020/3/31学习笔记-day30

//重写hashCode按照id
public void test2(){
    Set set =null;
    set = new HashSet();
    set.add(new Student(1L,"TOM",21));
    set.add(new Student(2L,"JACK",24));
    set.add(new Student(3L,"MARRY",22));
    set.add(new Student(4L,"JAMES",23));
    set.add(new Student(5L,"CURRY",20));
    set.add(new Student(5L,"CURRY",20));
    this.showCollection(set);
}
public int hashCode(){
    return (int)this.id;
}

2020/3/31学习笔记-day30

String内部也重写了hashCode方法

2020/3/31学习笔记-day30

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}
public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}
相关标签: Web学习