Java容器之子接口[9]

一、Set接口

Set接口是Collection的子接口,没有定义新的方法,常用的一个实现该接口的类为HashSet

常用方法:

  •  boolean

    addAll(Collection<? extends E> c)

  •  
     booleanretainAll(Collection<?> c)
package Container;

import java.util.HashSet;
import java.util.Set;

public class TestSet {
	public static void main(String args[]){
		Set s1=new HashSet();
		s1.add("a");s1.add("b");s1.add("c");
		Set s2=new HashSet();
		s2.add("d");s2.add("b");s2.add("a");
		Set sn=new HashSet(s1);//将s1复制到sn,因为通过要进行两个操作,addaAll和retainAll   S1会被覆盖
		s1.addAll(s2);
		sn.retainAll(s2);
		System.out.println(s1);
		System.out.println(s2);
		
	}

}
结果:[d, b, c, a]
[d, b, a]

二、List接口

List接口是Collection接口的子接口,实现该接口的主要的类有:ArrayList和LinkedList,其中ArrayList是底层利用数组实现的容器,LinkedList是底层利用链表实现的容器。

常用方法

  •  Eset(int index, E element)
  •  Eget(int index)
package Container;

import java.util.ArrayList;
import java.util.List;

public class TestList1 {
public static void main(String args[]){
	List l1=new ArrayList();
	for(int i=0;i<5;i++)
	l1.add("a"+i);
	System.out.println(l1);
	l1.set(3, "a100");
	System.out.println(l1);
	System.out.println(l1.get(4));
}
   
    
}
结果:[a0, a1, a2, a3, a4]
[a0, a1, a2, a100, a4]
a4

 

Collections类

java.util.Collections:提供了一些静态方法实现了基于List容器的一些算法

常用算法:

static
<T> void
sort(List<T> list, Comparator<? super T> c)
static voidshuffle(List<?> list)
static
<T> int
binarySearch(List<? extends Comparable<? super T>> list, T key)
static voidreverse(List<?> lis
static
<T> void
copy(List<? super T> dest, List<? extends T> src

 

package Container;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class TestList2 {
public static void main(String args[]){
	List l2=new LinkedList();
	for (int i=0;i<=5;i++)
		l2.add("a"+i);
	System.out.println(l2);
	Collections.sort(l2);//静态方法,类名。方法
	System.out.println(l2);
	Collections.reverse(l2);
	System.out.println(l2);
    Collections.shuffle(l2);
	System.out.println(l2);	
}
}
结果:[a0, a1, a2, a3, a4, a5]
[a0, a1, a2, a3, a4, a5]
[a5, a4, a3, a2, a1, a0]
[a5, a4, a2, a3, a1, a0]

三、Map接口

实现Map接口的类常用来存储键-值对,Map接口的实现类有HashMap和TreeMap

常用方法:

 Vget(Object key)
 Vput(K key, V value)
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;


public class TestMap {
public static void main(String args[]){
	Map m1=new HashMap();
	Map m2=new TreeMap();
	m1.put("1", 1);
	m1.put("2", new Integer(2));
	System.out.println(m1);
	m2.put("first", "1");
	m2.put("second", "2");
	System.out.println(m2);
	m1.put("1", "first");
	System.out.println(m1);
	System.out.println(m1.hashCode());
}
}

 

转载于:https://my.oschina.net/kongjunli/blog/735072

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值