数组、字符容器,对象容器

1.数组

     ·几种定义方式

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * Created by 111 on 2016/2/24. 
  3.  */  
  4. public class ArrayTest {  
  5.     public static void main(String [] args){  
  6.         int [] arr1;                                    //未初始化不可以使用  
  7.         String [] arr3,arr4 = new String[]{"aaa","bbb"};//可以定义多个数组,变量已知  
  8.         int arr5[] = new int[]{};                       //已初始化,只能定义一个数组  
  9.         int [] arr2 = new int[4];  
  10.         for (int i = 0,length=arr2.length;i<length;i++){//为数组插入数据  
  11.             arr2[i] = 4;  
  12.         }  
  13.         System.out.println(arr2.length);                //数组长度(0-(length-1))  
  14.     }  
  15. }  

2.String

    ·String一旦被初始化就不会被改变(String属于对象,对象的不可改变是指对象的状态不可改变,更具体就是对象内部成员变量不可改变)

          解析源码(Java 1.7 一部分):

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public final class String  
  2.     implements java.io.Serializable, Comparable<String>, CharSequence {  
  3.     /** The value is used for character storage. */  
  4.     private final char value[];  
  5.   
  6.     /** Cache the hash code for the string */  
  7.     private int hash; // Default to 0  
  8.   
  9.     /** use serialVersionUID from JDK 1.0.2 for interoperability */  
  10.     private static final long serialVersionUID = -6849794470754667710L;  
  11. }  
               ★从源码中可以看出String是利用了数组来存储,而用于存储的value是final类型(被final修饰的变量属于常量,被final修饰的方法不能被覆盖,被final修饰的类不能被继承),源码中也并没有提供value的get/set方法,所以一旦值固定,就不能被改变。

               ★但是为什么replace/replaceAll等其他String提供的方法仍然能返回同一个呢,我们知道对象有对象和对象的引用(保存的是对象的地址)之分,对象储存在堆中,对象的引用存储在栈中,这里其实是对象的引用指向了另一个新的对象。查看源码可知:其利用了StringBuffer来操作String中的数据。

Java.lang.String 的replace源码:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.     * Replaces each substring of this string that matches the literal target 
  3.     * sequence with the specified literal replacement sequence. The 
  4.     * replacement proceeds from the beginning of the string to the end, for 
  5.     * example, replacing "aa" with "b" in the string "aaa" will result in 
  6.     * "ba" rather than "ab". 
  7.     * 
  8.     * @param  target The sequence of char values to be replaced 
  9.     * @param  replacement The replacement sequence of char values 
  10.     * @return  The resulting string 
  11.     * @throws NullPointerException if <code>target</code> or 
  12.     *         <code>replacement</code> is <code>null</code>. 
  13.     * @since 1.5 
  14.     */  
  15.    public String replace(CharSequence target, CharSequence replacement) {  
  16.        return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(  
  17.                this).replaceAll(Matcher.quoteReplacement(replacement.toString()));  
  18.    }  

java.util.regex.Matcher 的replaceAll()方法

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.      * Replaces every subsequence of the input sequence that matches the 
  3.      * pattern with the given replacement string. 
  4.      * 
  5.      * <p> This method first resets this matcher.  It then scans the input 
  6.      * sequence looking for matches of the pattern.  Characters that are not 
  7.      * part of any match are appended directly to the result string; each match 
  8.      * is replaced in the result by the replacement string.  The replacement 
  9.      * string may contain references to captured subsequences as in the {@link 
  10.      * #appendReplacement appendReplacement} method. 
  11.      * 
  12.      * <p> Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in 
  13.      * the replacement string may cause the results to be different than if it 
  14.      * were being treated as a literal replacement string. Dollar signs may be 
  15.      * treated as references to captured subsequences as described above, and 
  16.      * backslashes are used to escape literal characters in the replacement 
  17.      * string. 
  18.      * 
  19.      * <p> Given the regular expression <tt>a*b</tt>, the input 
  20.      * <tt>"aabfooaabfooabfoob"</tt>, and the replacement string 
  21.      * <tt>"-"</tt>, an invocation of this method on a matcher for that 
  22.      * expression would yield the string <tt>"-foo-foo-foo-"</tt>. 
  23.      * 
  24.      * <p> Invoking this method changes this matcher's state.  If the matcher 
  25.      * is to be used in further matching operations then it should first be 
  26.      * reset.  </p> 
  27.      * 
  28.      * @param  replacement 
  29.      *         The replacement string 
  30.      * 
  31.      * @return  The string constructed by replacing each matching subsequence 
  32.      *          by the replacement string, substituting captured subsequences 
  33.      *          as needed 
  34.      */  
  35.     public String replaceAll(String replacement) {  
  36.         reset();  
  37.         boolean result = find();  
  38.         if (result) {  
  39.             StringBuffer sb = new StringBuffer();  
  40.             do {  
  41.                 appendReplacement(sb, replacement);  
  42.                 result = find();  
  43.             } while (result);  
  44.             appendTail(sb);  
  45.             return sb.toString();  
  46.         }  
  47.         return text.toString();  
  48.     }  
                  ★这里说不能被改变,是自身不能改变,但是我们可以利用反射来改变,这里被final修饰的也是一个数组对象,属于引用变量,这里final只能限制不能指向其他的数组对象,但是我们可以对数组中的内容进行修改。通过反射的方法获取到value这个数组字段,然后对数组中的数据进行修改。

参考代码:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import java.lang.reflect.Field;  
  2.   
  3. /** 
  4.  * Created by 111 on 2016/2/28. 
  5.  */  
  6. public class Demo2 {  
  7.     public static void main(String[]args)throws Exception{  
  8.         String s = "ABCDEFG";  
  9. //        Class stringClass = Class.forName("java.lang.String");  
  10. //        Class stringClass = s.getClass();  
  11.         Class stringClass = String.class;//三种获取类的方式  
  12.         Field valueField = stringClass.getDeclaredField("value");//获取需要的字段  
  13.         valueField.setAccessible(true);    //设置可访问权限  
  14.         char [] value = (char[])valueField.get(s);//获得该字段的值  
  15.         value[0] = 'B';  
  16.         System.out.println(s);//输出BBCDEFG  
  17.     }  
  18. }  
      · string内部提供的方法:

       ——length();

       ——isEmpty();

       ——charAt():0<=x<length();

       ——getBytes(String charsetName):

       。。。

    ·关于字符串的一些操作

           ★将字符串反转(String并未提供该方法,StringBuffer提供了该方法reverse())

                ①仿照StringBuffer中的reverse()方法

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import java.lang.reflect.Field;  
  2.   
  3. /** 
  4.  * Created by 111 on 2016/2/28. 
  5.  */  
  6. public class Demo3 {  
  7.     public static void main(String [] args) throws Exception{  
  8.         String s = "ABCDE";  
  9.         Class sClass = Class.forName("java.lang.String");  
  10.         Field valueField = sClass.getDeclaredField("value");  
  11.         valueField.setAccessible(true);  
  12.         char [] value = (char[])valueField.get(s);  
  13.         int l = s.length()-1;  
  14.         for (int j=(l-1)>>1;j>=0;--j){//有符号右移,高位补0,若无符号右移,高位补1  
  15.             char temp = value[j];  
  16.             char temp2 = value[l-j];//StringBuffer中下面会有一个验证  
  17.             value[l-j] = temp;  
  18.             value[j] = temp2;  
  19.         }  
  20.         System.out.println(s);  
  21.     }  
  22. }  

             ②使用递归

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * Created by 111 on 2016/2/29. 
  3.  */  
  4. public class Demo4 {  
  5.     public static void main(String [] args){  
  6.         String s = "ABCDE";  
  7.         String str = reverse(s);  
  8.         System.out.println(str);  
  9.     }  
  10.     private static String reverse(String s){  
  11.         if (s.isEmpty())return s;  
  12.         return reverse(s.substring(1))+s.charAt(0);  
  13.     }  
  14. }  

       ③遍历

   

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * Created by 111 on 2016/2/29. 
  3.  */  
  4. public class Demo5 {  
  5.     public static void main(String [] args){  
  6.         String str = "ABCDE";  
  7.         String s = ""//如果数据量大的话可以使用StringBuilder,多线程使用StringBuffer  
  8.         for (int i =str.length()-1;i>=0;i--){  
  9.             s+=str.charAt(i);                //sb.append(str.charAt(i));  
  10.         }  
  11.         System.out.println(s);  
  12.     }  
  13. }  
       ★字符串去重

         ①放入Set集合中

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import java.util.HashSet;  
  2. import java.util.Set;  
  3.   
  4. /** 
  5.  * Created by 111 on 2016/2/29. 
  6.  */  
  7. public class Demo6 {  
  8.     public static void main(String [] args){  
  9.         String str = "AABCDAEFE";  
  10.         Set set = new HashSet();  
  11.         for (int i=0,l=str.length();i<l;i++){  
  12.             set.add(str.charAt(i));  
  13.         }  
  14.         System.out.println(set.toString());  
  15.     }  
  16. }  

             ②循环判断

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3.   
  4. /** 
  5.  * Created by 111 on 2016/2/29. 
  6.  */  
  7. public class Demo7 {  
  8.     public static void main(String[]args){  
  9.         String str = "AABCDAEFE";  
  10.         List<String> list = new ArrayList<String>();  
  11.         for (int i = 0,len=str.length();i<len;i++){  
  12.             if (!list.contains(String.valueOf(str.charAt(i)))){  //char转为String  
  13.                 list.add(String.valueOf(str.charAt(i)));  
  14.             }  
  15.         }  
  16.         System.out.println(list.toString());  
  17.     }  
  18. }  

3.StringBuffer、StringBuilder   (append)(初始化容量为16字符

       ·与String相比特点:★长度可变

                           ★可以存储不同基本数据类型

                           ★可以对字符串进行修改(append,delete,insert,replace)

     

       ·StringBuffer:线程安全

       ·StringBuilder:单线程

4.Collection 集合类(add)(Vector和ArrayList 初始化容量为10

   ·特点:★存储对象,不可以存储基本数据类型

          ★长度可变

   ·Collection 

         ··List(有序、元素有角标、元素可重复)指的是存入和取出的顺序一致:特有方法可操作角标的方法   Iterator it = list.iterator()

              ···Vector    : list接口大小可变数组的实现,包括null,是同步的,所以查询速度相对较慢(被sychronized修饰)

              ···ArrayList : list接口大小可变数组的实现,包括null,不同步的,数组有角标,所以查询速度快

              ···LinkedList:  list的链接列表的实现,     包括null,  不同步的,链表实现所以增删速度快

         ··Set(无序、元素不可重复)

              ···HashSet   : 包括null, 不同步的,基于哈希表(实际上是HashMap 实例)(开辟一个原有4/3大小的集合,默认16)

                    ····LinkedHashSet

5.Map

    ·Map<Key,Value>  :an object that maps keys to values,key 不能重复。一个key最多映射一个value

           ·HashMap    :哈希表的实现,允许空键和空值,是不同步的

           ·Hashtable  :哈希表的实现 ,非空对象可以作为键或者值,同步的

                  ·Properties

           ·treeMap :二叉树的底层实现,可用于给Map集合中键进行排序

           ★map的几种遍历方法

[java]  view plain  copy
  1. package com.raipeng.work.container;  
  2.   
  3. import java.util.*;  
  4.   
  5. /** 
  6.  * Created by 111 on 2016/2/29. 
  7.  */  
  8. public class ListTest {  
  9.     public static void main(String [] args){  
  10.         Map<Integer,String> map = new HashMap();  
  11.         map.put(1,"abc");  
  12.         map.put(2,"def");  
  13.         //keySet()  
  14.         Set<Integer> keySet = map.keySet();  
  15.         for (Integer key :keySet){//keySet的for循环  
  16.             System.out.println("key:"+key+"value:"+map.get(key));  
  17.         }  
  18.         Iterator<Integer> it = keySet.iterator();//keySet的iterator  
  19.         while (it.hasNext()){  
  20.             Integer key =it.next();  
  21.             System.out.println(key+map.get(key).toString()+"");  
  22.         }  
  23.         //entrySet()  
  24.         Set<Map.Entry<Integer,String>> entry = map.entrySet();  
  25.         for (Map.Entry<Integer,String> en:map.entrySet()){//entrySet的for循环  
  26.             System.out.println("key:"+en.getKey()+"value:"+en.getValue());  
  27.         }  
  28.         Iterator<Map.Entry<Integer,String>> iterator = entry.iterator();//entrySet的iterator  
  29.         while (iterator.hasNext()){  
  30.             Map.Entry<Integer,String> entry1 = iterator.next();  
  31.             Integer key = entry1.getKey();  
  32.             String value = entry1.getValue();  
  33.             System.out.println("key"+key+"value"+value);  
  34.         }  
  35.     }  
  36. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值