JAVA 集合方法

Collection---接口:
Set接口
*HashSet---实现类(以哈希码表为底层的实现机制)
TreeSet---实现类(以二叉树(一种数据结构)为底层的实现机制)
没有顺序, 不可以重复(可以互相equals就叫重复)
List接口
*ArrayList---实现类(以数组为底层的实现机制)
LinkedList---实现类(以链表为底层的实现机制)
有顺序, 可以重复

Map接口(键值对)
*HashMap---实现类
TreeMap---实现类
每次往里放的时候都是一对一对的

Collection接口的方法
Collection接口的使用
Collection<String> c = new ArrayList<String>();
问题: 为什么不直接写ArrayList<String> a = new ArrayList<String>();
c.add(参数类型必须是Object)

c.remove方法: 通过判断两个对象是否互相的equals来确定是不是该删除该对象, 自定义的类, 需要自己重写父类的equals方法
重写equals方法, 也应该重写hashCode方法

hashCode通常用来做索引, 一个对象通过它的hashCode的值可以找到它在内存中的地址, 所以两个对象如果equals了, 而且又要作为索引的情况下, hashCode的值必须相等

List接口:
ArrayList(API中说初始容量为10的, 注意这个问题), LinkedList
有顺序, 可以重复添加
get
set(有一个返回值要注意 !)
add
remove(int)
remove(Object)
indexOf
lastIndexOf
retainAll(Collection)----返回一个boolean值, 当list的内容被改变的时候返回true, 否则返回false

Map接口
HashMap(哈希表做索引), TreeMap(二叉树做索引)
键值对(键不能重复, 什么情况算是重复)
put
get
remove
containsKey
containsValue
size
isEmpty
putAll
clear

public class Ji {
	
     public static void main( String[ ] args){
    	 
    	List list1 = new ArrayList();
 		
 		for (int i = 0; i < 5; i++) {
 			list1.add("string" + i);
 			}
    	 System.out.println(list1);
    	 System.out.println(list1.get(2));
    	 System.out.println(list1.set(1,"哈哈"));
    	 System.out.println(list1);
    	 System.out.println(list1.remove(3));
    	 System.out.println(list1);
    	 System.out.println(list1.indexOf("哈哈"));
    	 System.out.println(list1.lastIndexOf("哈哈"));
    	 
    	 
     }

  

public class Ji {
	
     public static void main( String[ ] args){
    	 
    	/*List list1 = new ArrayList();
 		
 		for (int i = 0; i < 5; i++) {
 			list1.add("string" + i);
 			}
    	 System.out.println(list1);
    	 System.out.println(list1.get(2));
    	 System.out.println(list1.set(1,"哈哈"));
    	 System.out.println(list1);
    	 System.out.println(list1.remove(3));
    	 System.out.println(list1);
    	 System.out.println(list1.indexOf("哈哈"));
    	 System.out.println(list1.lastIndexOf("哈哈"));
    	 
    	 
     }
     */
    	 Map map = new HashMap( );
 		for (int i = 0; i < 5; i++) {
 			
 			map.put(i, new Person("name"+ i ));
 		}
 		System.out.println(map);
 		map.put(5, new Person("新人"));
 		System.out.println(map);
 		map.put(1, new Person("又来个新人"));
 		System.out.println(map);
 		System.out.println(map.get(2));
 		System.out.println(map.remove(1));
 		System.out.println(map);
 		System.out.println(map.remove(0, new Person("name0")));
 		System.out.println(map);
 		System.out.println(map.containsKey(4));
 		System.out.println(map.containsValue(new Person("name0")));
 		
 		System.out.println(map.size());
 		System.out.println(map.isEmpty());
 		}
     class Person{
    	 String name;
    	 public Person( String name){
    		 this.name = name;
    		 
    	 }
     }

}
     

  

原文地址:https://www.cnblogs.com/nsl714745601/p/7240589.html