JavaSE Collection及其常用方法

一、Collection概述

  • 集合中不能直接存储基本数据类型,也不能存储Java对象,只是存储java对象的内存地址
  • 存放在集合中的类型,一定要重写equals()方法

二、Collection中的常用方法

1. add()

  • boolean add(Object e)
  • 向集合中添加元素
import java.util.ArrayList;
import java.util.Collection;

public class Test {
	public static void main(String[] args) {
		/**
		 * 向集合中添加元素 add()
		 */
		// 创建一个集合对象
		// Collection c = new Collection(); // 接口是抽象的,无法实例化
		// 多态
		Collection c = new ArrayList();
		c.add(100); // 自动装箱:java5的新特性,实际上是放进去了一个对象的内存地址:Integer x = new Integer(100);
		c.add(true); // 自动装箱
		c.add(new Object());
		c.add(new Student());
	}
}

class Student{
	
}

2. size()

  • int size()
  • 获取集合中元素的个数(不是容量)
import java.util.ArrayList;
import java.util.Collection;

public class Test {
	public static void main(String[] args) {
		/**
		 * 获取集合中元素的个数 size()
		 */
		// 创建一个集合对象
		// Collection c = new Collection(); // 接口是抽象的,无法实例化
		// 多态
		Collection c = new ArrayList();
		c.add(100); // 自动装箱:java5的新特性,实际上是放进去了一个对象的内存地址:Integer x = new Integer(100);
		c.add(true); // 自动装箱
		c.add(new Object());
		c.add(new Student());
		
        System.out.println("集合中元素个数是:" + c.size()); // 4
	}
}

class Student{
	
}

3. clear()

  • void clear()
  • 清空集合
import java.util.ArrayList;
import java.util.Collection;

public class Test {
	public static void main(String[] args) {
		/**
		 * 清空集合 clear()
		 */
		// 创建一个集合对象
		// Collection c = new Collection(); // 接口是抽象的,无法实例化
		// 多态
		Collection c = new ArrayList();
		c.add(100); // 自动装箱:java5的新特性,实际上是放进去了一个对象的内存地址:Integer x = new Integer(100);
		c.add(true); // 自动装箱
		c.add(new Object());
		c.add(new Student());
		
        System.out.println("集合中元素个数是:" + c.size()); // 4
        
        c.clear();
        System.out.println("集合中元素个数是:" + c.size()); // 0
	}
}

class Student{
	
}

4. contains()

  • boolean contains(Object o)
  • 判断当前集合中是否包含某元素,包含返回true,不包含返回false
  • 底层实质上调用了equals()方法
  • 存放在集合中的类型,一定要重写equals()方法

4.1 测试一

import java.util.ArrayList;
import java.util.Collection;

public class Test {
	public static void main(String[] args) {
		/**
		 * 判断当前集合中是否包含元素o,包含返回true,不包含返回false contains()
		 * 实质上底层调用了equals方法进行比对,equals方法返回true,就表示包含这个元素
		 */
		// 创建集合对象
		Collection c = new ArrayList();

		// 向集合中存储元素
		String s1 = new String("abc"); // s1 = 内存地址
		c.add(s1); // 放进去了一个"abc"

		String s2 = new String("123"); // s2 = 内存地址
		c.add(s2);

		// 集合中元素的个数
		System.out.println("元素的个数是:" + c.size()); // 2

		String s3 = new String("abc"); // x = 0x5555
		// 判断c集合中是否包含s3(实质上是判断c集合是否存在"abc",没有判断内存地址,因为equals()比较的是内容,不是内存地址)
		System.out.println(c.contains(s3)); // true
	}
}

4.2 测试二

import java.util.ArrayList;
import java.util.Collection;

public class Test {
	public static void main(String[] args) {
		// 创建集合对象
		Collection c = new ArrayList();
		// 创建用户对象
		User u1 = new User("lzj");
		User u2 = new User("lzj");
		// 加入集合
		c.add(u1);

		// 判断集合中是否包含u2
		// 没有重写equals之前:这个结果是false
		// System.out.println(c.contains(u2)); // false
		// 重写equals方法之后,比较的时候会比较内容,即name
		System.out.println(c.contains(u2)); // true

		c.remove(u2);
		System.out.println(c.size()); // 0

		/*
		 * Integer x = new Integer(10000); 
		 * c.add(x);
		 * 
		 * Integer y = new Integer(10000); 
		 * Integer已经重写了equals()方法
		 * System.out.println(c.contains(y)); // true
		 */
	}
}

class User {
	private String name;

	public User() {
	}

	public User(String name) {
		this.name = name;
	}

	// 重写equals方法,只要name一样,就是同一个人(不再比较对象的内存地址了,比较内容)
	public boolean equals(Object o) {
		if (o == null || !(o instanceof User))
			return false;
		if (o == this)
			return true;
		User u = (User) o;
		return u.name.equals(this.name);
	}

}

4.3 源码分析

  • ArrayList底层contains()源码:
public boolean contains(Object o) {
     return indexOf(o) >= 0; // 调用indexOf()方法
}
public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i])) // 调用equals()方法
                    return i;
        }
        return -1;
    }
  • LinkedList底层contains()源码:
public boolean contains(Object o) {
     return indexOf(o) != -1; // 调用indexOf()方法
}
public int indexOf(Object o) {
        int index = 0;
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) // 调用equals()方法
                    return index;
                index++;
            }
        }
        return -1;
    }
  • HashSet底层contains()源码:
public boolean contains(Object o) {
    return map.containsKey(o); // 调用containsKey()方法
}
public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null; // 调用getNode()方法
    }
final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

5. remove()

  • boolean remove(Object o)
  • 删除集合中某个元素
  • 底层实质上调用了equals()方法

5.1 测试一

import java.util.ArrayList;
import java.util.Collection;

public class Test {
	public static void main(String[] args) {
		/**
		 * 删除集合中某个元素 remove()
		 */
		Collection c = new ArrayList();
		c.add("hello");
        c.add("world");
        c.add(1);
        c.remove("hello");
        System.out.println("集合中元素个数是:" + c.size()); // 2
	}
}

5.2 测试二

import java.util.ArrayList;
import java.util.Collection;

public class Test {
	public static void main(String[] args) {
		/**
		 * 删除集合中某个元素 remove() 
		 * 底层实质上调用了equals()方法
		 */
		// 创建集合对象
		Collection c = new ArrayList();
		// 创建字符串对象
		String s1 = new String("hello");

		c.add(s1);

		// 创建了字符串对象
		String s2 = new String("hello");
		// 删除s2
		c.remove(s2); // s1.equals(s2) java认为s1和s2是一样的,删除一个s2就是删除一个s1
		System.out.println(c.size()); // 0
	}
}

5.3 源码分析

    • ArrayList底层remove()源码:
public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

6. isEmpty()

  • boolean isEmpty()
  • 判断该集合是否为空
import java.util.ArrayList;
import java.util.Collection;

public class Test {
	public static void main(String[] args) {
		/**
		 * 判断该集合中元素的个数是否为0 isEmpty()
		 */
		Collection c = new ArrayList();
		c.add("hello");
        c.add("world");
        System.out.println(c.isEmpty()); // false
	}
}

7. toArray()

  • Object[] toArray()
  • 集合转换成数组
import java.util.ArrayList;
import java.util.Collection;

public class Test {
	public static void main(String[] args) {
		/**
		 * 集合转换成数组 toArray()
		 */
		Collection c = new ArrayList();
		c.add("hello");
		c.add("world");
		Object[] objs = c.toArray();
		for (int i = 0; i < objs.length; i++) {
			// 遍历数组
			Object o = objs[i];
			System.out.println(o);
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jayco江柯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值