Collection 和Collections的区别|、String的getBytes方法

1.比较Collection 和Collections的区别=====
  
(1)、java.util.Collection 是一个集合接口。它提供了对集合对象进行基本操作的通用接口方法。Collection接口在Java 类库中有很多具体的实现。Collection接口的意义是为各种具体的集合提供了最大化的统一操作方式.
 
(2)2、java.util.Collections 是一个包装类。它包含有各种有关集合操作的静态多态方法。此类不能实例化,就像一个工具类,服务于Java的Collection框架.
 
package com.pf;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class CollectionsDemo {
  public static void main(String[] args) {
    List<Integer> list=new ArrayList<Integer>();
   //产生20以内的随机整数,并将其放在list集合中
    list.add(new Random().nextInt(20));
    list.add(new Random().nextInt(20));
    list.add(new Random().nextInt(20));
    list.add(new Random().nextInt(20));
    for(Integer inta:list)
    { 
     System.out.println(inta);
    }
    System.out.println("排序过后:");
    // 调用Collections工具类的方法对list对象进行操作
    Collections.reverse(list);//反转
    Collections.sort(list);//升序
    for(Integer inta:list)
    { 
     System.out.println(inta);
    }
    System.out.println("最大数:"+Collections.max(list));

 2               ====.==getBytes方法=====作用:获取字符串的字节数组
该方法使用平台的默认字符集将此String编码为byte序列,并将结果存储到一个新的byte数组。
 
语法1  getBytes()
 
 该方法将返回所得byte数组。
 
示例  使用getBytes ()函数将字符串strCom编码为byte序列,将返回值赋给str数组,并输出返回值。
 String strCom = "java";              //定义一个字符串
 byte[] str = strCom.getBytes();      //将指定字符串编码为byte序列
 for(int i=0;i<str.length;i++){       //输出返回数组
   System.out.println(str[i]);
 }
 
语法2  getBytes(Charset charset)
 
charset:用于编码String的Charset。
 
示例  使用getBytes ()函数将字符串strCom用Java 虚拟机的默认字符集编码为byte序列,将返回值赋给str数组,并输出返回值。
 String strCom = "java";               //定义一个字符串
 byte[] str = strCom.getBytes(Charset.defaultCharset());
 //将指定字符串用Java 虚拟机的默认编码为byte序列
 for(int i=0;i<str.length;i++){       //输出返回数组
   System.out.println(str[i]);
 }
 
语法3  getBytes(String charsetName)
 
 charsetName:charsetName为受支持的 charset。
 
示例  使用getBytes()函数将字符串strCom用GBK编码为byte序列,将返回值赋给str数组,并输出返回值。
 String strCom = "java";        //定义一个字符串
 byte[] str;
 try {
   //将指定字符串用GBK编码为byte序列
   str = strCom.getBytes("GBK");
   for (int i = 0; i < str.length; i++) {    //输出返回数组
    System.out.println(str[i]);
   }
 } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章