Java之集合工具类

Collections工具类

collections是集合中的一个工具类,封装的都是静态方法。

1.sort(List)方法可对list中的元素进行排序。

2.而实现sort(list,comparator)方法的调用,要新建class,实现Comparator接口,并复写compare方法。具体可参照选课后续中对Student自定义数据进行排序的代码实现。

3.binarySearch(list,key)方法是使用二分搜索法获取list中指定对象的索引,前提是保证list处于有序状态。其中,key值是要索引的元素。

public void demo_binarysort()
	{
		List<String> list = new ArrayList<String>();
		
		list.add("aasddf");
		
		list.add("vdvdf");
		
		list.add("sf");
		
		list.add("dfsf");
		
		Collections.sort(list);
		
		System.out.println(list);
		
		int index = Collections.binarySearch(list, "sf");
		
		System.out.println(index);
	}

4. Object max(Collection,Comparator)可获取Collection集合中的最大值。不指定比较器时,使用默认排序法。

5. void fill(list,value)可将list中所有元素全部替换成value

如 Collections.fill(list,"a");//将list中全部元素替换成a

syso(list);

6.List shuffle(list)对list元素进行随机排序

Arrays工具类

List Arrays.asList 能将数组转化为List集合。

但是由于数组长度固定,不能使用集合的增删方法对转化的list进行操作。

如果数组中的元素是对象(如String),那么转成集合时,直接将数组中的元素作为集合中的元素进行存储。

如果数组中的元素是基本类型数值(如int),那么会将该数组作为集合中的元素进行存储。

同理,集合也可以转成数组。使用ToArray方法。此时需要传入指定类型的数组。如果数组长度小于集合的size,那么该方法会创建一个和原集合长度相同且元素也相同的数组。如果数组长度大于集合的size,那么大于的部分补充null。所以建议将数组长度定义为集合.size

ForEach语句

格式:

for(类型  变量 :Collection集合 or 数组)

对map中的key和value进行遍历:

public static void demo3()
	{
		Map<Integer,String> map = new HashMap<Integer,String>();
		
		map.put(1,"zhangsan");
		
		map.put(2, "lisi");
		
		map.put(3, "wangwu");
		
		for(Integer key : map.keySet())
		{
			String value = map.get(key);
			
			System.out.println(key+","+value);
		}
	}

猜你喜欢

转载自blog.csdn.net/weixin_42139212/article/details/84556500